Net Core中使用Autofac

 

 

 

第一步:在Nuget中安装Autofac包

第二步:在Nuget中安装Autofac.Extensions.DependencyInjection(MVC项目已经默认安装了,控制台应用程序需要安装)

S

tartup类

在Startup类中,将ConfigureServices方法的返回值修改成IServiceProvider,

方式一

然后在这个方法中添加我们自定义的 return AutofacConfigure.Register(services)  这段代码

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;

namespace NetCoreApp
{
    public class Startup
    {
        
        public IConfiguration Configuration { get; } //构造函数注入:Configuration用于读取配置文件的
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        //这是公共语言运行时(CLR)环境所调用的一个方法,这个方法这样就是向我们的内置IOC容器中注册服务的(我们也可以不要这个方法,我们可以用AutofacIOC容器)
		//注意将这个方法的返回值由原来的void改为IServiceProvider
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {            
            services.Configure(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
          
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSession();

            //将.netcore的默认IOC容器ServiceCollection替换成Autufac的IOC容器AutofacServiceProvider
            return AutofacConfigure.Register(services);             
        }
    }
}

自定义Autofac配置类

using System;
using System.Reflection;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

namespace NetCoreApp
{
    public class AutofacConfigure //Autofac配置类
    {
        public static AutofacServiceProvider Register(IServiceCollection services)
        {           
            ContainerBuilder builder = new Autofac.ContainerBuilder();

            //builder.RegisterType().As().PropertiesAutowired();直接对类进行注册

            Assembly entityAss = Assembly.Load("Entity"); //对Entity这个类库进行里的类进行集体注册
            Type[] etypes = entityAss.GetTypes();
            builder.RegisterTypes(etypes).AsImplementedInterfaces().PropertiesAutowired();

                       
            Assembly webAss = Assembly.Load("NetCoreApp");//对当前项目中的类进行注册
            Type[] wtypes = webAss.GetTypes();
            builder.RegisterTypes(wtypes).AsImplementedInterfaces().PropertiesAutowired();

            builder.Populate(services);
            var container = builder.Build();
            return new AutofacServiceProvider(container);
        }
    }
}

在IBLL中定义了一个IUser接口

namespace IBLL
{
    public interface IUser
    {
        string Sum();
    }
}

在Entity类库中定义了一个User类,继承这个IUser

using IBLL;

namespace Entity
{
    public class User : IUser
    {
        public string Sum()
        {
            return "你好,世界";
        }
    }
}

在控制器中使用

​
using IBLL;
using Microsoft.AspNetCore.Mvc;

namespace NetCoreApp.Controllers
{
    public class HomeController : Controller
    {
        private IUser _user { get; set; }
        public HomeController(IUser user)//构造函数
        {
            this._user = user; 
        }
        public IActionResult Index()
        {
            var msg = _user.Sum();
            return Content(msg);
        }
    }
}

​

方式二

using Autofac;
using System;
using System.Reflection;

namespace NetCoreApp
{
    public class AutofacModule: Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            //注入服务

            Assembly entityAss = Assembly.Load("Entity");
            Type[] etypes = entityAss.GetTypes();
            builder.RegisterTypes(etypes).AsImplementedInterfaces().PropertiesAutowired();

            //builder.RegisterType().As().PropertiesAutowired();

            Assembly webAss = Assembly.Load("NetCoreApp");
            Type[] wtypes = webAss.GetTypes();
            builder.RegisterTypes(wtypes).AsImplementedInterfaces().PropertiesAutowired();
        }
    }
}

 

你可能感兴趣的:(Autofac,NetCore)