使用Autofac简单扩展dotnet core ioc

项目中引入如下nuget package

<ItemGroup>
    <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="7.2.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyModel" Version="6.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.3.0" />
  </ItemGroup>

定义三个用于标记的接口,可以自行修改

public interface ISingletonIocTag
    { }
    public interface IScopedIocTag
    { }
    public interface ITransientIocTag
    { }

简单扩展IOC服务注册

.net 3.x

using System.Linq;
using System.Runtime.Loader;

using Autofac;
using Autofac.Extensions.DependencyInjection;

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.Hosting;

    public static class AutofacExtensions
    {
        public static IHostBuilder UseAutofac(this IHostBuilder host)
        {
            host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
            host.ConfigureContainer<ContainerBuilder>(container =>
            {
                var libs = DependencyContext.Default.CompileLibraries.Where(lib => lib.Serviceable == false && lib.Type == "project").Select(lib => lib.Name).ToList();

                var assemblies = libs.Select(lib => AssemblyLoadContext.Default.LoadFromAssemblyName(new System.Reflection.AssemblyName(lib))).ToArray();

                container
                    .RegisterAssemblyTypes(assemblies)
                    .Where(type => type.IsAbstract == false && type.IsAssignableTo<ISingletonIocTag>())
                    .AsSelf()
                    .AsImplementedInterfaces()
                    .SingleInstance()
                    .PropertiesAutowired();

                container
                    .RegisterAssemblyTypes(assemblies)
                    .Where(type => type.IsAbstract == false && type.IsAssignableTo<IScopedIocTag>())
                    .AsSelf()
                    .AsImplementedInterfaces()
                    .InstancePerLifetimeScope()
                    .PropertiesAutowired();

                container
                    .RegisterAssemblyTypes(assemblies)
                    .Where(type => type.IsAbstract == false && type.IsAssignableTo<ITransientIocTag>())
                    .AsSelf()
                    .AsImplementedInterfaces()
                    .InstancePerDependency()
                    .PropertiesAutowired();

                container
                    .RegisterAssemblyTypes(assemblies)
                    .Where(type => type.IsAbstract == false && type.IsAssignableTo<ControllerBase>())
                    .AsSelf()
                    .InstancePerDependency()
                    .PropertiesAutowired();
            });

            return host;
        }
    }

dotnet 5.x、6.x

using System.Linq;
using System.Runtime.Loader;

using Autofac;
using Autofac.Extensions.DependencyInjection;

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.Hosting;

    public static class AutofacExtensions
    {
        public static IHostBuilder UseAutofac(this IHostBuilder host)
        {
            host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
            host.ConfigureContainer<ContainerBuilder>(container =>
            {
                var libs = DependencyContext.Default.CompileLibraries.Where(lib => lib.Serviceable == false && lib.Type == "project").Select(lib => lib.Name).ToList();

                var assemblies = libs.Select(lib => AssemblyLoadContext.Default.LoadFromAssemblyName(new System.Reflection.AssemblyName(lib))).ToArray();

                container
                    .RegisterAssemblyTypes(assemblies)
                    .Where(type => type.IsAbstract == false && type.IsAssignableTo(typeof(ISingletonIocTag)))
                    .AsSelf()
                    .AsImplementedInterfaces()
                    .SingleInstance()
                    .PropertiesAutowired();

                container
                    .RegisterAssemblyTypes(assemblies)
                    .Where(type => type.IsAbstract == false && type.IsAssignableTo(typeof(IScopedIocTag)))
                    .AsSelf()
                    .AsImplementedInterfaces()
                    .InstancePerLifetimeScope()
                    .PropertiesAutowired();

                container
                    .RegisterAssemblyTypes(assemblies)
                    .Where(type => type.IsAbstract == false && type.IsAssignableTo(typeof(ITransientIocTag)))
                    .AsSelf()
                    .AsImplementedInterfaces()
                    .InstancePerDependency()
                    .PropertiesAutowired();

                container
                    .RegisterAssemblyTypes(assemblies)
                    .Where(type => type.IsAbstract == false && type.IsAssignableTo(typeof(ControllerBase)))
                    .AsSelf()
                    .InstancePerDependency()
                    .PropertiesAutowired();
            });

            return host;
        }
    }

替换IOC容器

dotnet 3.x、5.x

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

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

---

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddControllersAsServices();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Dotnet3WebApiDemo", Version = "v1" });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Dotnet3WebApiDemo v1"));
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

dotnet 6.x

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers().AddControllersAsServices();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Host.UseAutofac();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值