Autofac Mvc Webapi注入ノート

2007 ワード

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では属性でOKです
 
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>();