问题
I had the problem with Autofac and memory leak in NServiceBus Scheduler. But fortunately I fixed that.
Autofac and memory leak with BeginLifetimeScope / DbContext has been disposed / C# asp.net
But now I'm trying to refactor this part slightly.
My code:
public void Start()
{
List<Type> jobTypes = new List<Type> { typeof(ExpiryDateTask) };
foreach (var jobType in jobTypes)
{
_schedule.Every(TimeSpan.FromSeconds(30), () =>
{
using (var scope = _lifetimeScope.BeginLifetimeScope())
{
var job = scope.Resolve<IJob>();
job.Run();
}
});
}
}
How can I refactor this part:
List<Type> jobTypes = new List<Type> { typeof(ExpiryDateTask) };
- that list should be filled somehow by all Types of Tasks that implement IJob interface.var job = scope.Resolve<IJob>();
I think this is wrong and should looks more likevar job = resolveJob(jobType)
- so basically based on the type.
@EDIT
Point (1) solved by Getting all types that implement an interface
回答1:
For the second part of your question, you can use Autofac child container registrations to do what you want:
foreach (var jobType in jobTypes)
{
_schedule.Every(TimeSpan.FromSeconds(30), () =>
{
using (var scope = _lifetimeScope.BeginLifetimeScope(builder =>
{
builder.RegisterType(jobType).As<IJob>();
}))
{
var job = scope.Resolve<IJob>();
job.Run();
}
});
}
That way, classes that implement IJob
will also benefit from constructor dependency injection.
来源:https://stackoverflow.com/questions/50622158/autofac-list-of-types-that-implements-interface-c-sharp-asp-net