Autofac前面寫了那麼多篇, 其實就是為了今天這一篇, Autofac在MVC和WebApi中的應用.
一、目錄結構
先看一下我的目錄結構吧, 搭了個非常簡單的架構, IOC(web), IBLL, BLL, IDAL, DAL, Helper
public interface ITestBll { void Say(List<string> msg); }
我裡面都是為了實現Say方法的.
public class TestBll : ITestBll { public void Say(List<string> msg) { msg.Add("進入TestBll中的方法Say"); var dal = IocContainer.Create<ITestDal>(); dal.Say(msg); } }
ITestDal , TestDal 和上面這兩個內容其實是一樣的, 只是分層不一樣. 這裡就不貼了.
二、實現
在Application_Start方法的末尾位置, 調用一個注冊方法.
protected void MvcInit() { IocContainer.RegisterMvc(); IocContainer.RegisterWebApi(); IocContainer.RegisterTypes(System.Reflection.Assembly.Load("BLL").GetTypes()); IocContainer.RegisterTypes(System.Reflection.Assembly.Load("DAL").GetTypes()); IocContainer.Build(); }
mvc, api 在asp.net中, 都是有自己的一套 ioc 方法的, 這裡其實也可以不寫. 不過這裡就是為了在這裡面的使用來說的.
在helper類庫中, 對autofac具體實現, 加了一些封裝.
public class IocContainer { private static ContainerBuilder builder; private static IContainer container; static IocContainer() { builder = new ContainerBuilder(); } #region 注冊接口 public static void RegisterTypeInstancePerLifetimeScope<T>() { builder.RegisterType<T>().InstancePerLifetimeScope(); } public static void RegisterTypeInstancePerDependency<T>() { builder.RegisterType<T>().InstancePerDependency(); } public static void RegisterTypeSingleInstance<T>() { builder.RegisterType<T>().SingleInstance(); } /// <summary> /// 注冊接口 /// </summary> /// <typeparam name="T">實現類型</typeparam> /// <typeparam name="IT">接口類型</typeparam> public static void RegisterType<T, IT>() { builder.RegisterType<T>().As<IT>(); } /// <summary> /// 自動裝配接口 /// </summary> /// <param name="types"></param> public static void RegisterTypes(params Type[] types) { builder.RegisterTypes(types).AsImplementedInterfaces(); } public static void RegisterType<T, IT>(string name) { builder.RegisterType<T>().Named<IT>(name); } public static void RegisterType<T, IT>(int key) { builder.RegisterType<T>().Keyed<IT>(key); } #endregion #region Build public static void Build() { container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //DependencyResolver.SetResolver(new AutofacWebApiDependencyResolver(container)); GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); } #endregion #region 注冊Mvc public static void RegisterMvc() { builder.RegisterControllers(Assembly.GetCallingAssembly()); } #endregion #region 注冊WebApi public static void RegisterWebApi() { builder.RegisterApiControllers(Assembly.GetCallingAssembly()); } #endregion #region 創建對象 public static T Create<T>() { return container.Resolve<T>(); } public static T Create<T>(string name) { return container.ResolveNamed<T>(name); } public static T Create<T>(int key) { return container.ResolveKeyed<T>(key); } public static object Create(Type t) { return container.Resolve(t); } #endregion }
做完上面的這些, 就可以在Controller, BLL, DAL中, 通過ioc的方式, 來獲取想要獲取到的類的實例