ser*_*0ne 5 c# dependency-injection .net-core
我正在使用IServiceCollection来为我的对象创建所需服务的列表。现在,我想实例化一个对象,并让DI容器解析该对象的依赖关系
例
// In my services config.
services
.AddTransient<IMyService, MyServiceImpl>();
// the object I want to create.
class SomeObject
{
public SomeObject(IMyService service)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
如何获得DI容器以创建类型SomeObject为注入依赖项的对象?(大概这就是对控制器的作用?)
注意:我不想存储SomeObject在服务集合中,我只想能够执行以下操作...
SomeObject obj = startup.ServiceProvider.Resolve<SomeObject>();
Run Code Online (Sandbox Code Playgroud)
...基本原理:我不必将所有控制器都添加到服务容器中,所以我也看不到为什么也必须添加SomeObject它!
如对已标记答案的注释中所述,您可以使用ActivatorUtilities.CreateInstance方法。.NET Core(我认为自1.0版以来)已经存在此功能。
请参阅:https : //docs.microsoft.com/zh-cn/dotnet/api/microsoft.extensions.dependencyinjection.activatorutilities.createinstance
这有点粗糙,但这有效
public static class ServiceProviderExtensions
{
public static TResult CreateInstance<TResult>(this IServiceProvider provider) where TResult : class
{
ConstructorInfo constructor = typeof(TResult).GetConstructors()[0];
if(constructor != null)
{
object[] args = constructor
.GetParameters()
.Select(o => o.ParameterType)
.Select(o => provider.GetService(o))
.ToArray();
return Activator.CreateInstance(typeof(TResult), args) as TResult;
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)