WebAPI2使用AutoFac依赖注入完整解决方案。
WebApi2上进行依赖注入,在百度里能搜到的的完整解决方案的文章少之又少,缺胳膊断腿。
和MVC5依赖注入的不同之处,并且需要注意的地方,标记在注释当中。上Global代码:
namespace S2S.WebApi { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { //----AutoFac DI------ var builder = new ContainerBuilder(); SetupResolveRules(builder); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //RegisterApiControllers方法 var container = builder.Build(); HttpConfiguration config = GlobalConfiguration.Configuration;//注意此处HttpConfiguration类的 config对象,一定不要new,要从GlobalConfiguration获取 config.DependencyResolver = (new AutofacWebApiDependencyResolver(container)); //注意此处与MVC依赖注入不同 //--------------------------------------------------------- AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } /// <summary> /// AutoFac /// </summary> /// <param name="builder"></param> private static void SetupResolveRules(ContainerBuilder builder) { var assembly = Assembly.Load("s2s.BLL"); //根据程序集名称加载程序集 builder.RegisterAssemblyTypes(assembly).SingleInstance();//每次都返回同一个实例 builder.RegisterAssemblyTypes(assembly).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces(); } } }
也没有太多需要解释的地方,Controller中还是构造器注入。开发中已经亲测有效。
可以收藏,以后查看。