緣由:html
+ 若高層依賴於底層,那麼底層的變更也會致使高層的變更,這就會致使模塊的複用性下降並且大大提升了開發的成本。 + 如果依賴於抽象的話,那麼是比較穩定的,底層或者高層的變更都不會互相影響
控制反轉背後的核心思想是, 咱們再也不將類綁定在應用裏,讓類本身去 "new up" 他們的依賴, 而是反過來在類的構造方法中將依賴傳遞進去git
尋找到相關實例,將其賦給接口對象。github
public class SomeType : IService { }
在代碼中能夠經過兩種方法訪問該類型(SomeType):c#
SomeType
IService
組件 指的是 SomeType
而它暴露的 服務 指的是 SomeType
和 IService
.設計模式
public HomeController(IGradeService gradeService) { _gradeService = gradeService; } public ActionResult Index() { var model = _gradeService.GetAllGrade().ToList(); return View(model); }
public void Application_Start() { ... //依賴注入 var builder = new ContainerBuilder(); builder.RegisterType().As().InstancePerHttpRequest(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) .AsImplementedInterfaces(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
namespace MvcApp5.Models { public interface IDependency { } }
public class HomeController : Controller { private readonly IModelCar _carmodel; private readonly IModelUser _usermodel; public HomeController(IModelCar carmodel,IModelUser usermodel) { _carmodel = carmodel; _usermodel = usermodel; } public ActionResult Index() { ViewBag.Message = "修改此模板以快速啓動你的 ASP.NET MVC 應用程序。"; var carname=_carmodel.GetCarName(); var username = _usermodel.GetUserName(); return View(); } }
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); var builder=RegisterService(); DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build())); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); } private ContainerBuilder RegisterService() { var builder = new ContainerBuilder(); var baseType=typeof(IDependency); var assemblys=AppDomain.CurrentDomain.GetAssemblies().ToList(); var AllServices = assemblys .SelectMany(s => s.GetTypes()) .Where(p => baseType.IsAssignableFrom(p)&&p!=baseType); builder.RegisterControllers(assemblys.ToArray()); builder.RegisterAssemblyTypes(assemblys.ToArray()) .Where(t =>baseType.IsAssignableFrom(t)&&t!=baseType) .AsImplementedInterfaces().InstancePerLifetimeScope(); return builder; } }
public class ValuesController : ApiController { private readonly IUserService _UserService; public ValuesController(IUserService UserService) { _UserService = UserService; } public IHttpActionResult Get(string name) { string str = _UserService.Set(name); return Ok(str); } }
public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { #region 自動注入 //建立autofac管理註冊類的容器實例 var builder = new ContainerBuilder(); HttpConfiguration config = GlobalConfiguration.Configuration; 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(); //註冊Api類型 builder.RegisterApiControllers(assemblies).PropertiesAutowired(); //builder.RegisterFilterProvider(); builder.RegisterWebApiFilterProvider(config); var container = builder.Build(); //註冊api容器須要使用HttpConfiguration對象 config.DependencyResolver = new AutofacWebApiDependencyResolver(container); //註冊解析 DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); #endregion AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } }