I. Introduction
purpose
1. Dependency injection purpose is to decouple.
2 does not depend on the specific type, but depends abstract class or interface, called dependency inversion.
3. Control inversion i.e. IoC (Inversion of Control), which calls the right in conventional direct control of the program code object to the container, and the assembly is achieved through the container management object assembly. The so-called "inversion of control" concept is the transfer of control of the Component Object, transferred from the program code itself to the outside of the container.
4. How to create a controller Microsoft DependencyResolver
The life cycle
1、InstancePerDependency
For each dependent on every call or create a new unique instance. This is also the default to create an instance of the way. The official document explained: Configure the component so that every dependent component or call to Resolve () gets a new, unique instance (default.)
2、InstancePerLifetimeScope
In the life cycle of a domain, or dependent on each call to create a single shared instance, and each a different life cycle domain instance is unique, not shared. The official document explained: Configure the component so that every dependent component or call to Resolve () within a single ILifetimeScope gets the same, shared instance Dependent components in different lifetime scopes will get different instances..
3、InstancePerMatchingLifetimeScope
In doing identifies a domain life cycle, or rely on each call to create a single shared instance. Sub-ID field played identifies the life cycle of a domain can be shared instance of the parent domain. If you do not find the life cycle of domain dot peen throughout inheritance hierarchy, the exception will be thrown: DependencyResolutionException . The official document explained: Configure the component so that every dependent component or call to Resolve () within a ILifetimeScope tagged with any of the provided tags value gets the same, shared instance Dependent components in lifetime scopes that are children of the tagged scope will share. parent's instance at The. the If CAN BE NO appropriately Tagged scope found in at The Hierarchy AN DependencyResolutionException IS thrown.
4、InstancePerOwned
In the example of the life cycle of a field have a lifecycle, each call-dependent component or Resolve () to create a single instance of the method for sharing, and the sub-instance of the lifetime field share the parent domain lifecycle. If you do not find a suitable domain has a life cycle of child instance in the inheritance hierarchy, an exception is thrown: DependencyResolutionException . The official document explained: Configure the component so that every dependent component or call to Resolve () within a ILifetimeScope created by an owned instance gets the same, shared instance Dependent components in lifetime scopes that are children of the owned instance scope will share the parent's. instance.. owned the If NO Appropriate scope instance found in at The Hierarchy CAN BE AN DependencyResolutionException IS thrown.
5、SingleInstance
Each time dependent or component calls Resolve () methods will give the same instance of a shared. In fact, Singleton pattern. The official document explained: Configure the component so that every dependent component or call to Resolve () gets the same, shared instance.
6, InstancePerHttpRequest (new version autofac recommended InstancePerRequest)
In a Http request context, a shared component instance. Only for asp.net mvc development.
官方文档解释:Share one instance of the component within the context of a single HTTP request.
Second, the common method
(1) builder.RegisterType <Object> ( ) As <Iobject> ():. Types and their register. The following example is register interface IDAL Examples SqlDAL
(2) IContainer.Resolve <IDAL> (): an instance of a parse interface. The last line of code such as the above examples is to parse the IDAL SqlDAL
(. 3) builder.RegisterType <Object> () Named <IObject> (String name):. Examples of a register different interfaces. Sometimes more than one class will inevitably encounter with a map interface, such as SqlDAL and OracleDAL have achieved IDAL interface in order to accurately obtain the type you want, you must take the name at the time of registration.
(4) IContainer.ResolveNamed <IDAL> ( string name): parsing an interface "named instance." The above example is to parse the last line of code named IDAL Example OracleDAL
(. 5) builder.RegisterType <Object> () as Keyed <IObject> (the Enum enum):. To enumerate way for instance a different interface registers. Sometimes we will achieve a different interface to distinguish enumeration, rather than a string,
(. 6) IContainer.ResolveKeyed <IDAL> (the Enum enum): Specific examples of parsing an interface based enumeration values. The above example is the last line of code parsing OracleDAL IDAL Specific examples of
(7) builder.RegisterType <Worker> ( ) InstancePerDependency ():. For controlling the life cycle of the object, a new instance is loaded at each instance, is the default this way
(8) builder.RegisterType <Worker> ( ) SingleInstance ():. For controlling the lifecycle of an object, an instance is returned at each instance the same loading
(9) IContainer.Resolve <T> ( NamedParameter namedParameter): in examples of parsing assign it a value T
Third, the configuration file
<?xml version="1.0"?> <configuration> <configSections> <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/> </configSections> <autofac defaultAssembly="ConsoleApplication1"> <components> <component type="ConsoleApplication1.SqlDAL, ConsoleApplication1" service="ConsoleApplication1.IDAL" /> </components> </autofac> </configuration>
static void Main(string[] args) { ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType<DBManager>(); builder.RegisterModule(new ConfigurationSettingsReader("autofac")); using (IContainer container = builder.Build()) { DBManager manager = container.Resolve<DBManager>(); manager.Add("INSERT INTO Persons VALUES ('Man', '25', 'WangW', 'Shanghai')"); }
Fourth, example
MVC5 example implemented features are: assembly registration, registered by services, property injection, the generic injection
global.cs
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); InitDependency(); StackExchange.Profiling.EntityFramework6.MiniProfilerEF6.Initialize(); } private void InitDependency() { ContainerBuilder builder = new ContainerBuilder(); The baseType type =typeof (IDependency); // automatically registered current assembly // builder.RegisterAssemblyTypes (Assembly.GetExecutingAssembly ()) AsImplementedInterfaces ();. // Register assembly Assembly Assemblies = Assembly.GetExecutingAssembly (); builder.RegisterAssemblyTypes (Assemblies) .Where (of the type ! => baseType.IsAssignableFrom (of the type) && type.IsAbstract) . .AsImplementedInterfaces () InstancePerLifetimeScope (); // ensure that the life cycle of an object based on a request // set of registration procedures referenced //var assemblyList = BuildManager.GetReferencedAssemblies().Cast<Assembly>().Where(assembly => assembly.GetTypes().Any(type => type.GetInterfaces().Contains(baseType))); //var enumerable = assemblyList as Assembly[] ?? assemblyList.ToArray(); //if (enumerable.Any()) //{ // builder.RegisterAssemblyTypes(enumerable) // .Where(type => type.GetInterfaces().Contains(baseType)) // .AsImplementedInterfaces().InstancePerLifetimeScope(); //} //注册指定的程序集 //自动注册了IStudentService、IUserServiceMathematics must be re Gassco Manage> (); // Two, Named registrar // builder.RegisterType <ChineseScorePlusManage> () Named <IChineseScoreManage> (ChineseScoreEnum.ChineseScorePlus.ToString ());. // interface is associated with a plurality of types // builder.RegisterType <ChineseScoreManage> (). Named <IChineseScoreManage> (ChineseScoreEnum.ChineseScore.ToString ()); // a plurality of interfaces associated with a type // three, Keyed registrar builder.RegisterType <ChineseScorePlusManage> () as Keyed <IChineseScoreManage> (ChineseScoreEnum.ChineseScorePlus);. / / a plurality of interface type associated builder.RegisterType <ChineseScoreManage> () as Keyed <IChineseScoreManage> (ChineseScoreEnum.ChineseScore);. // associated interface to a plurality of types //Generic registration, may return List <T> as determined by the container: List <string>, List < int> etc. // builder.RegisterGeneric (typeof (List <>)) of As (typeof (the IList <>)) InstancePerLifetimeScope.. (); // lifecycle // builder.RegisterType <StudentService> () of As <IStudentService> () InstancePerLifetimeScope ();.. @ thread-based or request is a request .. singleton or a common thread // builder.RegisterType <StudentService> () of As <IStudentService> () InstancePerDependency ();.. // service request will be returned for each separate instance // builder.RegisterType <StudentService> () of As <IStudentService> ().. the SingleInstance (); // singleton a common entire project .. // . builder.RegisterType <StudentService> () of As <IStudentService> (). InstancePerRequest ();// for MVC, or that a single request to each of ASP.NET .. Example builder.RegisterType <ServiceGetter> () of As <IServiceGetter> ();. // for an interface with a plurality of types associated builder.RegisterControllers (Assembly.GetExecutingAssembly ()) PropertiesAutowired ();. // property injection, appears not registered "is not defined for that object constructor with no arguments." builder.RegisterType <TestDbContext> () of As <IDbContext>. (). InstancePerLifetimeScope (); builder.RegisterGeneric ( typeof . (EfRepository <>)) of As ( typeof . (the IRepository <>)) InstancePerLifetimeScope (); // generic injection // builder.RegisterFilterProvider (); // injection characteristic, which characteristic to use related services IContainer Container = builder.Build (); DependencyResolver.SetResolver ( new new AutofacDependencyResolver (Container)); // generating chamber and provided to the MVC } protected void the Application_BeginRequest () { IF (Request.IsLocal) // This is to allow local access start monitoring, may write { MiniProfiler.Start () ; } } protected void the Application_EndRequest () { MiniProfiler.Stop (); } }
Controller
public class HomeController : Controller { private readonly IStudentService _studentService; private readonly ITeacherService _teacherService; private readonly IUserService _userService; public readonly UserService UserService; private readonly IEnglishScoreManage _englishScoreManage; private readonly IMathematicsScoreManage _mathematicsScoreManage; private IServiceGetter getter; public ICourseService CourseService { get; set; } private readonly IRepository<Student> _studentRrepository; public HomeController(IStudentService studentService, IUserService userService, ITeacherService teacherService, UserService userService1, IMathematicsScoreManage mathematicsScoreManage, IEnglishScoreManage englishScoreManage, IServiceGetter getter, IRepository<Student> studentRrepository) { _studentService = studentService; _userService = userService; _teacherService = teacherService; this.UserService = userService1; _mathematicsScoreManage = mathematicsScoreManage; _englishScoreManage = englishScoreManage; this.getter = getter; _studentRrepository = studentRrepository; } public ActionResult Index() { var name = ""; var student = _studentRrepository.GetById("4b900c95-7aac-4ae6-a122-287763856601"); if (student != null) { name = student.Name; } ViewBag.Name = _teacherService.GetName(); ViewBag.UserName1 = _userService.GetName(); ViewBag.UserName2 = UserService.GetName(); ViewBag.StudentName = _studentService.GetName() + "-" + name; ViewBag.CourseName = CourseService.GetName(); ViewBag.EnglishScore = _englishScoreManage.GetEnglishScore(); ViewBag.MathematicsScore = _mathematicsScoreManage.GetMathematicsScore(); //ViewBag.ChineseScore = getter.GetByName<IChineseScoreManage>(ChineseScoreEnum.ChineseScore.ToString()).GetScore(); //ViewBag.ChineseScorePlus = getter.GetByName<IChineseScoreManage>(ChineseScoreEnum.ChineseScorePlus.ToString()).GetScore(); ViewBag.ChineseScore = getter.GetByKey<ChineseScoreEnum, IChineseScoreManage>(ChineseScoreEnum.ChineseScore).GetScore(); ViewBag.ChineseScorePlus = getter.GetByKey<ChineseScoreEnum, IChineseScoreManage>(ChineseScoreEnum.ChineseScorePlus).GetScore(); return View(); } }
page
@{ ViewBag.Title = "Home Page"; } <div class="jumbotron"> <h1>ASP.NET</h1> </div> <div class="row"> <div class="col-md-4"> <h2>Teacher: @ViewBag.Name </h2> <p> CourseName: @ViewBag.CourseName </p> <p></p> </div> <div class="col-md-4"> <h2>User</h2> <p>接口注入:@ViewBag.UserName1</p> <p>类注入:@ViewBag.UserName2</p> </div> <div class="col-md-4"> <h2>Student: @ViewBag.StudentName</h2> <p>English:@ViewBag.EnglishScore</p> <p>Math: @ViewBag.MathematicsScore</p> <p>Chinese: @ViewBag.ChineseScore</p> <p>ChinesePlus:@ViewBag.ChineseScorePlus</p> </div> </div>
Download: https: //gitee.com/zmsofts/XinCunShanNianDaiMa/blob/master/EntityFrameworkExtension.rar
Note: codefirst development, can be used after the first migration
Reference article:
https://www.cnblogs.com/struggle999/p/6986903.html
https://www.cnblogs.com/gdsblog/p/6662987.html
https://www.cnblogs.com/kissdodog/p/3611799.html
https://www.cnblogs.com/fuyujian/p/4115474.html
http://www.cnblogs.com/tiantianle/category/779544.html