IoC 结构映射解析命名实例

本文关键字:实例 结构 映射 IoC | 更新日期: 2023-09-27 18:35:34

对于以下代码,我将如何根据名称进行解析?

public interface IService
{}
public class ServiceA : IService
{}
public class ServiceB : IService
{}
public class ClassA
{
    public IService service { get; set; }
    public ClassA(IService service)
    {
        this.service = service;
    }
}
public class ClassB
{
    public IService service { get; set; }
    public ClassB(IService service)
    {
        this.service = service;
    }
}

注册表:

public class MyRegistry : Registry
{
    public MyRegistry()
    {
        For<IService>().Add<ServiceA>().Ctor<IService>().Is(i => i.GetInstance<IService>("ServiceA")); // error
    }
}

用法:

container = new Container(new MyRegistry());
var test = container.GetInstance<ClassA>();

问题:

  • 对于 A 类 IService => 应该产生服务A
  • 对于 B IService => 应该产生服务B

  • 另外,有没有办法在构造函数中使用属性来指定特定类型的具体实现?(所以不必在配置中指定它?

IoC 结构映射解析命名实例

我们已经创建了自己的注册约定(请注意,此实现将每个插件系列注册为 Singleton):

    public class SingletonConvention<TPluginFamily> : IRegistrationConvention
{
    public void Process(Type type, Registry registry)
    {
        if (!type.IsConcrete() || !type.CanBeCreated() || !type.AllInterfaces().Contains(typeof(TPluginFamily)))
            return;
        registry.For(typeof(TPluginFamily)).Singleton().Use(type).Named(type.Name);
    }
}

然后在我们的注册表中(下面未经测试):

        Scan(y =>
        {
            y.With(new SingletonConvention<IService>());
            y.Assembly(Assembly.GetExecutingAssembly().FullName);
        });
        For<ClassA>()
            .Use<ClassA>()
            .Ctor<IService >("service").Is("service",x =>
            {
                var service = x.GetInstance<IService>().Named("ServiceA");
                return service;
            })

我让它像这样工作> @ozczcho的答案有所帮助。

谢谢
    For<ClassA>().Use<ClassA>().Ctor<IService>("service").Is<ServiceA>();
    For<ClassB>().Use<ClassB>().Ctor<IService>("service").Is<ServiceB>();