我正在嘗試使用 autofac 注冊開放的泛型型別以決議為派生型別
public interface IBackGroundJobHandler<T> where T: INotification
{
public Task Handle(T notification, CancellationToken cancellationToken);
}
public abstract class EventHandler<T> : IBackGroundJobHandler<T> where T : INotification
{
public abstract Task Handle(T notification, CancellationToken cancellationToken);
}
public class TestEventHandler : EventHandler<TestEvent>
{
public async override Task Handle(TestEvent notification, CancellationToken
cancellationToken)
{
await Task.Delay(20000);
System.Diagnostics.Debug.WriteLine("Test Event Finished");
}
}
public class SomeService<T> where T:INotfication
{
public SomeService(IBackGroundJobHandler<T> handler)
{
//sometask
}
}
我嘗試通過以下方式注冊它:
builder.RegisterGeneric(typeof(EventHandler<>)).As(typeof(IBackGroundJobHandler<>))
.InstancePerLifetimeScope();
IBackgroundJobHandler 未在服務建構式中決議。
我也試過:
builder.RegisterAssemblyTypes(typeof(EventHandler).GetTypeInfo().Assembly)
.AsClosedTypesOf(typeof(IBackGroundJobHandler<>)).InstancePerLifetimeScope();
我是autofac的新手,我該如何解決這個問題?
uj5u.com熱心網友回復:
我避免使用抽象類并簡單地使用通用介面 IBackGroundJobHandler<>
public class TestEventHandler : IBackGroundJobHandler<TestEvent>
{
public async override Task Handle(TestEvent notification, CancellationToken
cancellationToken)
{
//Task
}
}
在 Autofac 容器中注冊為:
builder.RegisterAssemblyTypes(typeof(IBackGroundEventHandler<>)
.GetTypeInfo().Assembly)
.AsClosedTypesOf(typeof(IBackGroundEventHandler<>))
.InstancePerLifetimeScope()
.AsImplementedInterfaces();
uj5u.com熱心網友回復:
EventHandler<T> 是一個抽象類,因此 Autofac 決議器無論如何都無法創建一個。
您還沒有注冊 TestEventHandler (例如),所以 Autofac 不知道它。
當您請求 IBackGroundJobHandler<TestEvent> 時,我假設您想要決議 TestEventHandler,但該類尚未注冊。
因此,鑒于您需要注冊 TestEventHandler,您可能無論如何都不需要那個 EventHandler<T> 抽象類。(我猜你認為這將是一種注冊從 EventHandler<T> 派生的所有類的方法)。TestEventHandler 可以只實作 IBackGroundJobHandler<TestEvent>。
class TestEventHandler : IBackGroundJobHandler<TestEvent>
{
public async Task Handle(TestEvent notification, CancellationToken cancellationToken)
{
// Process the Test Event
}
}
然后使用:
builder.RegisterType<TestEventHandler>()
.As<IBackGroundJobHandler<TestEvent>>()
.InstancePerLifetimeScope();
如果你有很多事件處理程式,那可能會很痛苦,所以我會使用反射來找到實作介面的類:
// Get the assembly that contains the implementors, assuming
// they are all in the same assembly as the TestEventHandler:
Assembly assembly = typeof(TestEventHandler).Assembly;
// Get all classes from assembly that implement the required interface
Type[] classesThatImplementIBackGroundJobHandler = assembly.GetTypes()
.Where(t => t.IsClass
&& t.GetInterfaces().Any(i =>
i.IsGenericType
&& i.GetGenericTypeDefinition() == typeof(IBackGroundJobHandler<>).GetGenericTypeDefinition())).ToArray();
// Register All Types that Implement our interface
builder.RegisterTypes(classesThatImplementIBackGrounJobHandler)
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/490310.html
