标签:成功 方法 alt context pre prot collect mode dex
原文:netcore使用Autofac实现依赖注入
在nuget中搜索“autofac”,添加下图中的两个程序集。他们的作用分别是autofac的核心库和依赖倒置的实现库。
修改Startup类的ConfigureServices方法
public IServiceProvider ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //1、实例一个容器 ContainerBuilder containerBuilder = new ContainerBuilder(); //2、接管系统内置服务(service默认的注册服务,还需要处理控制器实例相关的工作) containerBuilder.Populate(services); //3、注册服务之类型注册 containerBuilder.RegisterType<UserProvider>().As<IUserService>().SingleInstance(); //4、装载到容器 var iContainer = containerBuilder.Build(); //5、返回 return new AutofacServiceProvider(iContainer); }
public class CustomController : Controller { private IUserService _userService = null; /// <summary> /// 6、使用构造函数注入 /// </summary> /// <param name="userService"></param> public CustomController(IUserService userService) { this._userService = userService; } public IActionResult Index() { //7、调用服务方法 var userShowRel = _userService.Show(); return Content($"{userShowRel}成功"); } }
/// <summary> /// AutoFac依赖倒置注册模块 /// </summary> public class CustomAutoFacModule: Autofac.Module { /// <summary> /// 重写父类的Load方法 /// </summary> /// <param name="builder"></param> protected override void Load(ContainerBuilder builder) { builder.RegisterType<UserProvider>().As<IUserService>().SingleInstance();//感叹,这语法,真的是不能再爽了 //后面可以注册好多类型…… //后面可以注册好多类型…… //后面可以注册好多类型…… //后面可以注册好多类型…… } }
然后,修改注册方法
public IServiceProvider ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //1、实例一个容器 ContainerBuilder containerBuilder = new ContainerBuilder(); //2、接管系统内置服务(service默认的注册服务,还需要处理控制器实例相关的工作) containerBuilder.Populate(services); //3、注册服务之类型注册 //containerBuilder.RegisterType<UserProvider>().As<IUserService>().SingleInstance(); //3、注册服务之模块注册 containerBuilder.RegisterModule<Utility.CustomAutoFacModule>(); //4、装载到容器 var iContainer = containerBuilder.Build(); //5、返回 return new AutofacServiceProvider(iContainer); }
标签:成功 方法 alt context pre prot collect mode dex
原文地址:https://www.cnblogs.com/lonelyxmas/p/12549282.html