美文网首页
ASP.NET 中使用依赖注入框架 Autofac自动注入

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

作者: 段煜华 | 来源:发表于2019-09-29 19:21 被阅读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));

相关文章

网友评论

      本文标题:ASP.NET 中使用依赖注入框架 Autofac自动注入

      本文链接:https://www.haomeiwen.com/subject/qfmbuctx.html