asp.net core 2.1 ioc 依賴注入


1.生命周期

內置的IOC有三種生命周期:
Transient: Transient服務在每次被請求時都會被創建。這種生命周期比較適用於輕量級的無狀態服務。
Scoped: Scoped生命周期的服務是每次web請求被創建。
Singleton: Singleton生命能夠周期服務在第一被請求時創建,在后續的每個請求都會使用同一個實例。如果你的應用需要單例服務,推薦的做法是交給服務容器來負責單例的創建和生命周期管理,而不是自己來走這些事情。

在Startup的ConfigureServices方法中

調用方法services.AddSingleton(typeof(IMyService),new MyService());
也可以services.AddSingleton(typeof(IMyService),typeof(MyService));
最好還是services.AddSingleton<IMyService, MyService>();

因為這樣的話可以在MyService中通過構造函數注入其他服務。

2.注冊程序集的所有類

            //通過反射把所有服務接口進行了注入: 
            var serviceAsm = Assembly.Load(new AssemblyName("Service"));
            foreach (Type serviceType in serviceAsm.GetTypes()
            .Where(t => typeof(IServiceTag).IsAssignableFrom(t) && !t.GetTypeInfo().IsAbstract))
            {
                var interfaceTypes = serviceType.GetInterfaces();

                foreach (var interfaceType in interfaceTypes)
                {
                    services.AddSingleton(interfaceType, serviceType);
                }
            }

3.其他類注入

在其他類怎么使用注入?假如在ExceptionFilter中想調用IUserService怎么辦?要確保ExceptionFilter不是new出來的,而是IOC創建出來

services.AddSingleton<ExceptionFilter>(); 
//mvc core中注冊filter要在AddMvc的回調方法中注冊。
services.AddMvc(options =>
{
	var serviceProvider = services.BuildServiceProvider();
	var filter = serviceProvider.GetService<ExceptionFilter>();
	options.Filters.Add(filter);
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

手動獲取注入

在HttpContext可用的時候,也可以通過這種方法來解析服務:

 public IActionResult Index()
        {
         IMyDependency idService =  (IMyDependency)HttpContext.RequestServices.GetService(typeof(IMyDependency));
            return View();
        }

內置服務

asp.net mvc core中架注入了很多服務:
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1

最有用的就是IHostingEnvironment,其中主要成員有:WebRootPath屬性(wwwroot文件夾的物理路徑);ContentRootPath屬性(網站根目錄的物理路徑)。
Microsoft.AspNetCore.Hosting下的HostingEnvironmentExtensions下還提供了一些擴展方法:
IsDevelopment()是否是開發環境、IsProduction()是否是生產環境。
asp.net mvc core中沒有Server.MapPath()方法,根據你要定位的文件是不是在wwwroot下,你可以使用IHostingEnvironment. WebRootPath或者IHostingEnvironment. ContentRootPath來進行拼接。

    public class HomeController : Controller
    {
        private IHostingEnvironment iHostingEnvironment;

        public HomeController(IHostingEnvironment iHostingEnvironment)
        {
            this.iHostingEnvironment = iHostingEnvironment;
        }

        public IActionResult Index()
        {
            IHostingEnvironment host = new HostingEnvironment();
            host.WebRootPath = iHostingEnvironment.WebRootPath;
            host.ContentRootPath = iHostingEnvironment.ContentRootPath;
            host.ApplicationName = iHostingEnvironment.ApplicationName;
            host.EnvironmentName = iHostingEnvironment.EnvironmentName;

//            host.ContentRootFileProvider = iHostingEnvironment.ContentRootFileProvider;
//            host.WebRootFileProvider = iHostingEnvironment.WebRootFileProvider;

            return View(host);
        }
		...
	}

指定要由 web 主機使用的環境

Program.cs

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseEnvironment("Development") //指定要由 web 主機使用的環境。
                .UseStartup<Startup>();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM