【问题标题】:Creating a group of instances by name AutoFac按名称 AutoFac 创建一组实例
【发布时间】:2016-10-27 23:06:39
【问题描述】:

假设我有这个类:

public class ProcessObject : IProcessObject
{
    public string Name { get; set; }
    public ProcessObject(String Name)
    {
        this.Name = Name;
    }
}
public interface IProcessObject
{
    string Name { get; set; }
}

使用 AutoFac 作为 IoC-Container 我需要能够通过属性 Name 检索此类的唯一实例。

如果已经创建了某个名称的进程对象,我想返回该特定实例。

“使用示例代码”

ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<ProcessObject>();
builder.RegisterType<ProcessObject>().As<IProcessObject>().;
Container = builder.Build();
var obj1 = Container.Resolve<IProcessObject>(new NamedParameter("Name", "UniqueObjectByName1"));//Does not exist, create new instance
var obj2 = Container.Resolve<IProcessObject>(new NamedParameter("Name", "UniqueObjectByName1"));//An instance with this name exists, return that instance
var obj3 = Container.Resolve<IProcessObject>(new NamedParameter("Name", "UniqueObjectByName2"));//Does not exist, create new instance
Debug.WriteLine(obj1.Equals(obj2));//this is currently returning False, I would like it to be true
Debug.WriteLine(obj1.Equals(obj3));

在我当前的代码中,我通过在 ProcessObject 类中使用静态方法和用于跟踪我的所有 ProcessObjects 的单例列表来维护这一原则。

public static GetInstance(string Name)
{
    if (ProcessObjects.GetInstanceByName(Name) == null)
    {
        return new ProcessObject(Name);
    }
    else return ProcessObjects.GetInstanceByName(Name);
}

我还需要这个吗,或者 AutoFac 是否提供了一种解决方案来通过属性值返回唯一实例?

【问题讨论】:

    标签: c# autofac


    【解决方案1】:

    Autofac 不允许您动态命名对象或添加元数据,因此您仍然需要按名称缓存实例的工厂方法。

    但是,您可以将该工厂绑定到 Autofac,这样它看起来就像按名称缓存:

    // Let's say your factory is like this, where the cache
    // is stored in the instance, like a hash table. Adjust
    // your code as necessary.
    builder.RegisterType<MyCachingFactory>()
      .As<IFactory>()
      .SingleInstance();
    
    // Register a lambda that looks at the inbound set
    // of parameters and uses the registered factory
    // to resolve.
    builder.Register((c, p) =>
    {
      var name = p.Named<string>("Name");
      var factory = c.Resolve<IFactory>();
      return factory.GetInstanceByName(name);
    }).As<IProcessObject>();
    

    这样做,你应该能够做你正在寻找的东西:

    container.Resolve<IProcessObject>(new NamedParameter("Name", "a"));
    

    【讨论】:

    • 很棒的解决方案!我只有一个问题,您的示例中的方法是“factory.GetInstanceByName(name);”吗?和我的旧方法“GetInstance(string Name)”一样吗?或者你也会改变它?
    • 对不起,我当时正在查看您的工厂方法的主体,没有意识到它的名称不同。不管你叫什么,目的都是一样的。
    猜你喜欢
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    相关资源
    最近更新 更多