ASP.NET Core依賴注入&AutoFac

1. 前言

關於IOC模式和DI技術,網上已經有不少相關的探討,再次就不過多贅述了,只是簡單介紹一下它們的概念數據庫

  • 控制反轉(IoC/Inverse Of Control):   調用者將建立實例的控制權交給IOC容器,由容器建立,因此稱爲控制反轉。
  • 依賴注入(DI/Dependence injection) :   容器建立好實例後再注入給調用者的過程稱爲依賴注入。依賴注入技術讓咱們的應用程序實現了鬆散耦合

.NetFramewok和.Net Core的區別之一就是.net core全部的實例都是經過依賴注入來建立的。下面介紹一下ASP.NET CORE中如何使用依賴注入緩存

2.ASP.NET Core 中自帶的DI方式

ASP.NET Core自己已經集成了一個輕量級的IOC容器,開發者只須要定義好接口後,在Startup.cs的ConfigureServices方法裏使用對應生命週期的綁定方法便可cookie

例:框架

//註冊數據庫基礎操做
            services.AddScoped(typeof(IBLLConstruct<>), typeof(BLLConstruct<>)); //註冊緩存操做
            services.AddTransient(typeof(ICacheContext), typeof(CacheContext)); services.AddScoped(typeof(IAuth), typeof(LocalAuth)); services.AddSingleton(typeof(IHttpContextAccessor), typeof(HttpContextAccessor));
AddTransient:服務在每次請求時被建立
AddScoped:服務在每次請求時被建立,生命週期橫貫整次請求
AddSingleton:顧名思義Singleton(單例),服務在第一次請求時被建立(或者當咱們在ConfigureServices中指定建立某一實例並運行方法),其後的每次請求將沿用已建立服務

在這以後,咱們即可以將服務經過構造函數注入或者是屬性注入的方式注入到Controller,View(經過使用),甚至是Filter中(之前的項目是使用Unity將依賴注入到Filter,我的感受不如.net core中注入的簡潔)。

@inject

3.構造函數獲取實例

//數據訪問
        protected IBLLConstruct<UserInforMations> _repository { get; set; } //緩存
        protected ICacheContext _cache { get; set; } protected IAuth _auth { get; set; } public LoginService(IBLLConstruct<UserInforMations> repository, ICacheContext cache, IAuth auth) { this._cache = cache; this._repository = repository; this._auth = auth; }

流程大概就是這樣,咱們啓動項目來看一下它的執行順序ide

(1)容器建立實例函數

(2)構造函數獲取實例ui

4.使用AutoFac實現擴展

除了ASP.NETCore自帶的IOC容器外,咱們還可使用其餘成熟的DI框架,如Autofac,StructureMap等(本人只用過Unity,Autofac)。this

 (1)安裝autofacspa

    

(2)建立容器並註冊依賴.net

修改Startup.cs中ConfigureServices方法 不要忘了將ConfigureServices的返回值修改成IServiceProvider 

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_1); services.AddDbContext<DirectSellContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DBContext"), b => b.UseRowNumberForPaging())); //使用AutoFac進行注入
            return new AutofacServiceProvider(AutofacExt.InitAutofac(services)); }
(3)在AutofacExt類中建立容器並註冊依賴
private static IContainer _container; public static IContainer InitAutofac(IServiceCollection services) { var builder = new ContainerBuilder(); builder.RegisterType<GuidTransientAppService>().As<IGuidTransientAppService>(); builder.RegisterType<GuidScopedAppService>().As<IGuidScopedAppService>().InstancePerLifetimeScope(); builder.RegisterType<GuidSingletonAppService>().As<IGuidSingletonAppService>().SingleInstance(); builder.Populate(services); _container = builder.Build(); return _container; }

InstancePerLifetimeScope:同一個Lifetime生成的對象是同一個實例


SingleInstance:單例模式,每次調用,都會使用同一個實例化的對象;每次都用同一個對象;


InstancePerDependency:默認模式,每次調用,都會從新實例化對象;每次請求都建立一個新的對象;

(4)AutoFac批量註冊服務

經過以上方式能夠實現注入,可是咱們每定義一個接口,都要在AutoFac中註冊一次,可使用RegisterAssemblyTypes來避免這種重複勞動

反射獲取程序集

/// <summary>
        /// 根據程序集名稱獲取程序集 /// </summary>
        /// <param name="AssemblyName">程序集名稱</param>
        /// <returns></returns>
        public static Assembly GetAssemblyByName(String AssemblyName) { return Assembly.Load(AssemblyName); }

批量註冊

//註冊Service中的對象,Service中的類要以Service結尾,不然註冊失敗
            builder.RegisterAssemblyTypes(GetAssemblyByName("MyProject.Domain")). Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces();

這樣就實現了Domain層中以Service結尾的接口批量註冊 命名格式以下:

相關文章
相關標籤/搜索