在.net core 中,我们经常需要在其它类库中使用到IServiceProvider对象,可以新建:
public static IServiceCollection AddIoc(this IServiceCollection services) { return services; } public static IApplicationBuilder UseIoc(this IApplicationBuilder builder) { Ioc.ServiceProvider = builder.ApplicationServices; return builder; }
新建一个静态类,
public static class Ioc{ public static IServiceProvider ServiceProvider { get; set; } public static T GetService<T>() { return ServiceProvider.GetService<T>(); } public static T GetRequiredService<T>() { return ServiceProvider.GetRequiredService<T>(); } }
在startup.cs 中,ConfigureServices(IServiceCollection services)方法体,增加:
services.AddIoc();
在Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)方法体增加:
app.UseIoc();
现在在其它地方就可以直接使用,比如:
private ILogger Log = Ioc.GetService<ILogger>(); /// <summary> /// 包含应用程序的目录的绝对路径 /// </summary> private static string _contentRootPath = Ioc.GetRequiredService<IHostingEnvironment>().ContentRootPath;