亲宝软件园·资讯

展开

.net6引入autofac

汤姆茂 人气:0

引入NuGet

注册Autofac

在Program的var app = builder.Build();前加上这段代码

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
    builder.RegisterType<LogRecordsService>().As<ILogRecordsService>();
});

自动注册一个类库的服务

在Program注入autofac

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
    Assembly assembly = Assembly.Load(ServiceCore.GetAssemblyName());
    builder.RegisterAssemblyTypes(assembly)
           .AsImplementedInterfaces()
           .InstancePerDependency();
});

在要注册的类库下的某个类中,写一个方法

public static class ServiceCore
    {
        /// <summary>
        /// 获取程序集名称
        /// </summary>
        /// <returns></returns>
        public static string GetAssemblyName()
        {
            return Assembly.GetExecutingAssembly().GetName().Name;
        }
    }

加载全部内容

相关教程
猜你喜欢
用户评论