【问题标题】:AutoFac - Creating factories by enum with inheriting objectsAutoFac - 通过继承对象的枚举创建工厂
【发布时间】:2020-08-13 11:59:52
【问题描述】:
class Person : IParticipant {}
class Doctor: Person {}
class RandomParticipantGenerator : IParticipantGenerator{
    enum PersonType
    {
       Person,
       Doctor
    }
    public IParticipant GetParticipant(PersonType type, State state)
    {
    }
    public List<IParticipant> GetParticipants(PersonType type, State state, int numOfPeople)
    {
    }
}

我的程序中有这些类,我需要能够使用GetParticipant 方法生成Person/Doctor。它应该返回一个DocterPersonType 枚举是Doctor 一个新的Person 当提供的类型等于Person。 我正在使用一个简单的工厂方法,但我想使用 Autofac 来实现它。

我很想在这件事上得到一些帮助。

【问题讨论】:

  • 你能分享一下你到目前为止的尝试吗?
  • 直到现在我还没有使用 autofac。如果类型是人,我只是返回新人。现在我希望发生的是 autofac 根据类型为我提供选择的实现,我不知道该怎么做。

标签: c# .net-core dependency-injection autofac factory


【解决方案1】:

如果你想在 ASP.NET Core 中使用 Autofac,首先你应该配置 CreateHostBuilder 方法使用“Autofac”作为 IoC 容器。

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

然后您应该在Startup 类中添加ConfigureContainer 方法,以便为容器构建器提供自定义配置,如下所示:

public void ConfigureContainer(ContainerBuilder builder)
{
    builder.Register<IParticipant>((context, parameter) =>
    {
        var type = parameter.TypedAs<PersonType>();
        return type switch
        {
            PersonType.Person => new Person(),
            PersonType.Doctor => new Doctor(),
            _ => new Person(),// Or throw an exception
        };
    }).As<IParticipant>();
}

最后使用Func&lt;PersonType, IParticipant&gt; 代替IParticipant 声明_participantFactory 并像这样注入它:

public class SampleController : Controller
{
    private readonly Func<PersonType, IParticipant> _participantFactory;

    public SampleController (Func<PersonType, IParticipant> participantFactory)
    {
        _participantFactory = participantFactory;
    }

    [HttpGet]
    public IActionResult Get()
    {
        var participant = _participantFactory(PersonType.Person);
        return Ok(participant );
    }
}

【讨论】:

  • 谢谢,但我已经在做这样的事情了。我想使用 autofac 来实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-19
相关资源
最近更新 更多