zoukankan      html  css  js  c++  java
  • 用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

  • 相关阅读:
    Android Studio 个性化设置
    显示出eclipse文件层次
    2014在百度之星资格赛的第四个冠军Labyrinth
    android在单身的对象和一些数据的问题被释放
    Windows Server 2008 网管数据采集 努力做“日拱一卒“
    【 D3.js 入门系列 --- 9.1 】 生产饼图
    Android监视返回键
    JavaScript总结一下--创建对象
    PS多形式的部分之间复制“笨办法”
    PHP图片等比缩放,并添加Logo水印特定代码和盯
  • 原文地址:https://www.cnblogs.com/soundcode/p/11548148.html
Copyright © 2011-2022 走看看