隐藏

asp.net core 2.2 应用AutoFac进行自动扫描依赖注入实例代码

发布:2023/12/7 15:23:54作者:大数据 来源:大数据 浏览次数:528

nuget引用

public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

//services.AddScoped<IStudent,StudentImp>();

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

//autofac
var builder = new ContainerBuilder();
var baseType = typeof(IDependency);

//获取所有程序集进行扫描注入
var assemblies = Assembly.GetExecutingAssembly();//Assembly.Load("AutoFacTest");获取所有程序集,括号内为程序集名
builder.RegisterAssemblyTypes(assemblies).Where(type => type.GetInterfaces().Any(t => t == baseType && type != baseType)).AsImplementedInterfaces().SingleInstance();

//获取指定程序集进行扫描注入
var baseType1 = typeof(IDepend);//IDepend要与实现的接口和类放到同一程序集DDD.Domain中
var assemblies1 = Assembly.Load("DDD.Domain");//程序集名(类库名),有时可能与命名空间名称不一致
//baseType.IsAssignableFrom(t)t实例类型是否是当前baseType类型的实现,或t类型能否分配给当前类型baseType
builder.RegisterAssemblyTypes(assemblies1).Where(type => baseType1.IsAssignableFrom(type) && type != baseType1).AsImplementedInterfaces().InstancePerLifetimeScope();

builder.Populate(services);
return new AutofacServiceProvider(builder.Build());
}

声明:本站内容来源于原创和互联网,尊重作者版权,转载请注明来源网址,欢迎收藏,谢谢!