Autofac Mvc Webapi注入笔记

Autofac Mvc Webapi注入笔记

 

 private static void MvcIoc(ContainerBuilder builder)
        {
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).Where(t => !t.IsAbstract && (typeof(IHttpController).IsAssignableFrom(t) || typeof(IController).IsAssignableFrom(t))).InstancePerLifetimeScope();
            var container = builder.Build();
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);//ApiController WebApi注入 
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));//普通的MVC Controller 注入 
            
        }


MVC Filter注入 通过属性注入

builder.RegisterFilterProvider();

在Filter里通过属性就可以了

 

在Web Api请求中,没有注入,又需要获取其实例,可以这样获取

IDependencyScope dependencyScope = this.Request.GetDependencyScope();
ILifetimeScope requestLifetimeScope = dependencyScope.GetRequestLifetimeScope();
var customerService = requestLifetimeScope.Resolve<ICustomerService>();

  

在MVC中这样获取

var customerService = System.Web.Mvc.DependencyResolver.Current.GetService(typeof (ICustomerService));

或者
var customerService = System.Web.Mvc.DependencyResolver.Current.GetService<ICustomerService>();

  

 

你可能感兴趣的:(auto)