使用asp .net core 2.1使用自带的依赖注入,自带的依赖注入是构造函数注入。有些情况,构造函数注入并不能满足需求,所以需要使用其他方法获取指定实例。
public interface IEngine
{
/// <summary>
/// 类型构建
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
object Resolve(Type type);
}
public class GetEngine: IEngine
{
private IServiceProvider _serviceProvider;
public GetEngine(IServiceProvider serviceProvider)
{
this._serviceProvider = serviceProvider;
}
/// <summary>
/// 类型构建
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public object Resolve(Type type)
{
return _serviceProvider.GetService(type);
}
}
public class EnginContext
{
private static IEngine _engine;
[MethodImpl(MethodImplOptions.Synchronized)]
public static IEngine Initialize(IEngine engine)
{
if (_engine == null)
_engine = engine;
return _engine;
}
public static IEngine Current
{
get
{
return _engine;
}
}
}
需要在 Startup.cs
的 Configure
方法中调用,如下:
EnginContext.Initialize(new GetEngine(app.ApplicationServices));
完整示例如下:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
EnginContext.Initialize(new GetEngine(app.ApplicationServices));
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
新增一个类Information
进行测试,如下:
public class Information
{
private string Name => "Dot Net Core";
public string GetName()
{
return $"你好!{Name}";
}
}
在ConfigureServices
方法中将新增的类进行注入。
public void 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.AddTransient<Information>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
通过以下方式进行获取已经注入的对象。
EnginContext.Current.Resolve(typeof(Information));
使用示例如下:
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
var info= EnginContext.Current.Resolve(typeof(Information)) as Information;
ViewData["Message"] = info.GetName();
return View();
}
示例下载
示例
转载请注明:清风亦平凡 » asp .net core 不使用构造函数获得注入的对象
AddScoped
加入,通过这种形式获取是报错的。.net core
默认不允许通过此种访问,有验证作用域范围。如果一定要通过这种形式访问,可以取消作用域验证。在Program.cs
文件中使用.UseDefaultServiceProvider(options => { options.ValidateScopes = false; })
取消作用域验证。设置后,再使用此种方式也可获取成功,但并不建议使用。