实现界面的Autofac类型列表/C#Asp.net [英] Autofac list of types that implements interface / C# Asp.net

查看:80
本文介绍了实现界面的Autofac类型列表/C#Asp.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在NServiceBus Scheduler中遇到了Autofac和内存泄漏的问题.但是幸运的是我已经解决了.

I had the problem with Autofac and memory leak in NServiceBus Scheduler. But fortunately I fixed that.

使用BeginLifetimeScope/DbContext的Autofac和内存泄漏具有被处置/C#asp.net

但是现在我试图稍微重构这一部分.

But now I'm trying to refactor this part slightly.

我的代码:

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();
            }
        });
    }
}

我该如何重构这部分:

  1. List<Type> jobTypes = new List<Type> { typeof(ExpiryDateTask) };- 该列表应以某种方式由所有实现的任务类型填充 IJob界面.
  2. var job = scope.Resolve<IJob>();我认为这是错误的,应该看起来更像var job = resolveJob(jobType)-因此基本上基于类型.
  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


@EDIT

要点(1)通过获取实现接口的所有类型

推荐答案

对于问题的第二部分,您可以使用Autofac

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();
        }
    });
}

这样,实现IJob的类也将受益于构造函数依赖项注入.

That way, classes that implement IJob will also benefit from constructor dependency injection.

这篇关于实现界面的Autofac类型列表/C#Asp.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆