ASP.NET 中使用依赖注入框架 Autofac自动注入

2019-09-29  本文已影响0人  段煜华

方法一

//创建autofac管理注册类的容器实例
var builder = new ContainerBuilder();
Assembly[] assemblies = Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray();
//注册所有实现了 IDependency 接口的类型
Type baseType = typeof(IDependency);
builder.RegisterAssemblyTypes(assemblies)
        .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
        .AsSelf().AsImplementedInterfaces()
        .PropertiesAutowired().InstancePerLifetimeScope();

//注册MVC类型
builder.RegisterControllers(assemblies).PropertiesAutowired();
builder.RegisterFilterProvider();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

方法二

//创建autofac管理注册类的容器实例
var builder = new ContainerBuilder();
Assembly[] assemblies = Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray();
            
builder.RegisterAssemblyTypes(assemblies)
        .Where(t => t.Name.EndsWith("Repository"))
        .AsImplementedInterfaces()
        .AsSelf().AsImplementedInterfaces()
        .PropertiesAutowired().InstancePerLifetimeScope();

//注册MVC类型
builder.RegisterControllers(assemblies).PropertiesAutowired();
builder.RegisterFilterProvider();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
上一篇 下一篇

猜你喜欢

热点阅读