用Autofac替换.net core 内置容器

释放双眼,带上耳机,听听看~!

官方建议使用内置容器,但有些功能并不支持,如下:

  • 属性注入
  • 基于名称的注入
  • 子容器
  • 自定义生存期管理
  • Func<T> 支持

所以可以使用其他第三方IOC容器,如Autofac,下面为学习使用记录

一、首先准备了一个接口和其实现类

public interface ITestService
{
    string ShowMsg();
}

 

public class TestService: ITestService
{
    public string ShowMsg()
    {
        return \"test123\";
    }
}

 

二、安装Nuget 包

Autofac
Autofac.Extensions.DependencyInjection

 

三、在 Startup.ConfigureServices 中配置容器

注:使用第三方容器,Startup.ConfigureServices 必须返回 IServiceProvider。

  第一种方式,使用AutofacModule配置文件,原来代码修改为:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    // Add Autofac
    var containerBuilder = new ContainerBuilder();
    containerBuilder.RegisterModule<AutofacModule>();
    containerBuilder.Populate(services);
    var container = containerBuilder.Build();
    return new AutofacServiceProvider(container);
}

AutofacModule类如:

public class AutofacModule: Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<TestService>().As<ITestService>();
     //........... } }

 

  第二种方式

Startup.ConfigureServices如下修改

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    // Add Autofac
    var containerBuilder = new ContainerBuilder();
    //containerBuilder.RegisterModule<AutofacModule>();

   //自动注册该程序集下的所有接口
//netcore_autofac 为程序集命名空间 //InstancePerLifetimeScope:同一个Lifetime生成的对象是同一个实例 //SingleInstance:单例模式,每次调用,都会使用同一个实例化的对象;每次都用同一个对象; //InstancePerDependency:默认模式,每次调用,都会重新实例化对象;每次请求都创建一个新的对象; containerBuilder.RegisterAssemblyTypes(Assembly.Load(\"netcore_autofac\")).AsImplementedInterfaces().InstancePerLifetimeScope(); containerBuilder.Populate(services); var container = containerBuilder.Build(); return new AutofacServiceProvider(container); }

 

其他Autofac在.net core 的使用,请参考官方文档:https://docs.autofac.org/en/latest/integration/aspnetcore.html

给TA打赏
共{{data.count}}人
人已打赏
随笔日记

大利好 5G商用牌照近期将发放!“近期”有多近 最快或在本周

2020-11-9 5:13:40

随笔日记

算法—选择排序

2020-11-9 5:13:42

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索