[英]Dependency Injection in library in .NET
Lets say I have a CustomClass
class from a library that does somethings with a IWebHostEnvironment
service.假设我有一个来自与
CustomClass
服务相关的库的IWebHostEnvironment
。 And I wish to create and use this library inside a PageModel
like shown below:我希望在
PageModel
中创建和使用这个库,如下所示:
public class CustomClass
{
private readonly IWebHostEnvironment _environment;
public CustomClass(IWebHostEnvironment environment){
_environment = environment
}
public printEnvironment(){
Console.WriteLine(_environment.ContentRootPath);
}
}
public class Index : PageModel
{
private readonly IWebHostEnvironment _environment;
public Index(IWebHostEnvironment environment)
{
_environment = environment;
}
public void OnGet()
{
var cc = new CustomClass(environment);
cc.printEnvironment()
}
}
Is there a way to write this CustomClass
where it will automatically have access to the IWebHostEnvironment
without me having to inject it from the PageModel
?有没有办法编写这个
CustomClass
,它会自动访问IWebHostEnvironment
而我不必从PageModel
注入它?
I know this doesn't make much sense.我知道这没有多大意义。 The reason I'm asking this is because I'm upgrading a WebApp from
.NET Framework
, where dependency injections weren't a thing, to .NET Core
.我问这个的原因是因为我正在将 WebApp 从
.NET Framework
升级到.NET Core
,其中依赖注入不是问题。
Somewhere you must register this class of yours您必须在某处注册您的 class
// if you go without interface directly DI can instantiate your type
services.AddTransient(typeof(CustomClass));
// With interface will look like
services.AddTransient<ISomeInterface, CustomClass>();
// for this ^^ your class must be declared as
public class CustomClass : ISomeInterface .......
// THEN
public class CustomClass
{
private readonly IWebHostEnvironment _environment;
public CustomClass(IWebHostEnvironment environment){
_environment = environment
}
public printEnvironment(){
Console.WriteLine(_environment.ContentRootPath);
}
}
public class Index : PageModel
{
private readonly CustomClass _customClass;
public Index(CustomClass customClass)
{
_customClass = customClass;
}
public void OnGet()
{
//var cc = new CustomClass(environment); // no more needed
_customClass.printEnvironment()
}
}
// with interface will look like this
public class Index : PageModel
{
private readonly ISomeInterface _customClass;
public Index(ISomeInterface customClass)
{
_customClass = customClass;
}
public void OnGet()
{
_customClass.printEnvironment()
}
}
Bottom line here is - if your dependency injection knows how to get IWebHostEnvironment
, merely registering your class like这里的底线是 - 如果您的依赖注入知道如何获得
IWebHostEnvironment
,只需注册您的 class 就像
services.AddTransient(typeof(CustomClass));
or或者
services.AddTransient<ISomeInterface, CustomClass>();
will be enough to DI inject implementation of IWebHostEnvironment
into your custom class足以将
IWebHostEnvironment
的 DI 实现注入您的自定义 class
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.