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<CookiePolicyOptions>(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<User>().As<IUser>().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<User>().As<IUser>().PropertiesAutowired();

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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值