Autofac 注册封闭类型并在 运行 时间检索它们
Autofac Register closed types and retrieve them at run time
我有一个接受通用类型的接口 T
internal interface IQuestion<T> where T : IWithOptionsId
{
Task<T> Provide(Guid id);
}
接下来我将在多个class中实现这个接口。例如
public class SomeProvider : IQuestion<OptionsClass>
{
private readonly IRepository _repository;
public SomeProvider(IRepository repository)
{
_repository = repository;
}
public async Task<OptionsClass> Provide(Guid id)
...
}
为了用 outofac 注册这个,我使用了这个
Autofac.RegisterAssemblyTypes(
Assembly.GetExecutingAssembly())
.AsImplementedInterfaces()
.AsClosedTypesOf(typeof(IQuestion<>));
我的问题是这样的。我有这个接口的多个实例。如何在 运行 时间访问一次不同的实例?如果我的 IQuestion<T>
将接受 Options
class 并且还将接受 Answer
class 我如何才能获得那些 classes 的实例在 运行 时间?
我很确定您可以直接注入实例本身。不是很好的做法,但它应该有效:
public SomeClass(SomeProvider<OptionsClass> provider)
您也可以尝试在注册时创建一个命名实例,然后注入它。参见 this and this。
我有一个接受通用类型的接口 T
internal interface IQuestion<T> where T : IWithOptionsId
{
Task<T> Provide(Guid id);
}
接下来我将在多个class中实现这个接口。例如
public class SomeProvider : IQuestion<OptionsClass>
{
private readonly IRepository _repository;
public SomeProvider(IRepository repository)
{
_repository = repository;
}
public async Task<OptionsClass> Provide(Guid id)
...
}
为了用 outofac 注册这个,我使用了这个
Autofac.RegisterAssemblyTypes(
Assembly.GetExecutingAssembly())
.AsImplementedInterfaces()
.AsClosedTypesOf(typeof(IQuestion<>));
我的问题是这样的。我有这个接口的多个实例。如何在 运行 时间访问一次不同的实例?如果我的 IQuestion<T>
将接受 Options
class 并且还将接受 Answer
class 我如何才能获得那些 classes 的实例在 运行 时间?
我很确定您可以直接注入实例本身。不是很好的做法,但它应该有效:
public SomeClass(SomeProvider<OptionsClass> provider)
您也可以尝试在注册时创建一个命名实例,然后注入它。参见 this and this。