ASP.Net Core -- AutoFac

ASP.NET Core本身已经集成了一个轻量级的IOC容器,开发者只需要定义好接口后,在Startup.cs的ConfigureServices方法里使用对应生命周期的绑定方法即可,但是我们还可以使用其它的扩展进行服务注册

本案例将使用AutoFac进行服务注册,然后读取数据列表

1:框架大概结构:

Tutorials.Data:数据库上下文DbContext

Tutorials.IRepository:数据仓储接口

Tutorials.Repository:数据仓储接口实现类

Tutorials.IServices:业务服务接口(在控制器中调用该接口)

Tutorials.Services:业务服务接口实现类

2:具体实现如下:

在Model里新建一个实体类,Student.cs:

public class Student
    {
        public int  Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string LoginAccount { get; set; }
        public string LoginPwd { get; set; }
        public int Age { get; set; }
        public string Gender { get; set; }
        public string Address { get; set; }
        public string Hobby { get; set; }
        public long Phone { get; set; }
        public string IdNumber { get; set; }
    }

然后在IRepository新建一个仓储接口,IStudentRepository.cs:

public interface IStudentRepository
    {
        public List<Student> InitStudentList();
    }

在Repository里新建StudentRepository.cs实现仓储接口:

public class StudentRepository : IStudentRepository
    {
        private readonly DataContext _dbContext;

        public StudentRepository(DataContext dbContext)
        {
            _dbContext = dbContext;
        }
        public List<Student> InitStudentList()
        {
            return _dbContext.Student.ToList();
            
        }
    }

在IServcies里新建一个IStudentServcie.cs服务接口:

public interface IStudentServcie
    {
        public List<Student> InitStudentList();
    }

然后在Services里新建一个StudentServcie.cs实现服务接口,从仓储服务调用获取方法

public class StudentServcie : IStudentServcie
    {
        private readonly IStudentRepository _studentRepository;

        public StudentServcie(IStudentRepository studentRepository)
        {
            _studentRepository = studentRepository;
        }
        public List<Student> InitStudentList()
        {
            return _studentRepository.InitStudentList();
        }
    }

然后引入autofac扩展包:

Autofac.Extensions.DependencyInjection
Autofac.Extras.DynamicProxy

在program里添加autofac:

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

在startup里注册服务,首先新建一个类AutofacModuleRegister.cs:

public class AutofacModuleRegister : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            var basePath = AppContext.BaseDirectory;

            var serviceDllFile = Path.Combine(basePath, "Tutorials.Services.dll");
            var repositoryDllFile = Path.Combine(basePath, "Tutorials.Repository.dll");

            if (!(File.Exists(serviceDllFile) && File.Exists(repositoryDllFile)))
            {
                var msg = "Repository.dll和service.dll 丢失,因为项目解耦了,所以需要先F6编译,再F5运行,请检查 bin 文件夹,并拷贝。";
                throw new Exception(msg);
            }

            var assemblysServices = Assembly.LoadFrom(serviceDllFile);
            builder.RegisterAssemblyTypes(assemblysServices).AsImplementedInterfaces().InstancePerDependency();

            var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
            builder.RegisterAssemblyTypes(assemblysRepository).AsImplementedInterfaces().InstancePerDependency();
        }
    }

然后在Startup里添加服务:

public void ConfigureContainer(ContainerBuilder containerBuilder) 
        {
            containerBuilder.RegisterModule(new AutofacModuleRegister());
        }

这样基本就完成了,在控制器中实现注入,如下:

public class StudentController:Controller
    {
        private readonly IStudentServcie _studentServcie;

        public StudentController(IStudentServcie studentServcie)
        {
            _studentServcie = studentServcie;
        }
        public IActionResult Index() 
        {
            return View(_studentServcie.InitStudentList());
        }
    }

  

 

posted @ 2020-08-31 22:46  初晨~  阅读(546)  评论(0编辑  收藏  举报