如何在 Autofac 中使用工厂模式?

2024-04-14

目前我有以下内容:

public interface IService
{
    void Start();
}

public class FirstService : IService
{ }

我通过执行以下操作来解决该服务:

using (var scope = lifetimeScope.BeginLifetimeScope())
using (var service = scope.Resolve<IService>()) 
{ }

这很好用。然而,现在我想介绍第二个基于IService。所以我添加了以下内容:

public enum ServiceType {
   First = 0, Second
}

public class SecondService: IService
{ }

我该如何介绍需要的工厂ServiceType参数并解析正确的服务? (我可以使用switch但也许这不是最佳实践)


很久以前(久到我不完全记得它是如何工作的:-)我创建了这个片段 https://gist.github.com/gurustron/2fe50ff8a6173b431fae66e211082f1e这允许创建Func<TKey, TDep>工厂使用 Autofac 键控注册:

var builder = new ContainerBuilder();

builder.RegisterType<ImplOne>()
    .Keyed<IDependency>(MyTypeEnum.TypeOne)
    .SingleInstance();

builder.RegisterType<ImplTwo>()
    .Keyed<IDependency>(MyTypeEnum.TypeTwo)
    .SingleInstance();

builder.Register((c, p) =>
{
    var type = p.TypedAs<MyTypeEnum>();
    var resolve = c.Resolve<IIndex<MyTypeEnum, IDependency>>();
    return resolve[type];
});

var container = builder.Build();
var factory = container.Resolve<Func<MyTypeEnum, IDependency>>();
var dependency = factory(MyTypeEnum.TypeTwo);

public class ImplOne : IDependency {}

public class ImplTwo : IDependency {}

public interface IDependency{}

public enum MyTypeEnum
{
    TypeOne,
    TypeTwo
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Autofac 中使用工厂模式? 的相关文章

随机推荐