Autofac list of types that implements interface / C# Asp.net

眉间皱痕 提交于 2019-12-24 23:52:35

问题


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:

  1. List<Type> jobTypes = new List<Type> { typeof(ExpiryDateTask) }; - that list should be filled somehow by all Types of Tasks that implement IJob interface.
  2. var job = scope.Resolve<IJob>(); I think this is wrong and should looks more like var 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!