StructureMap:如何在构造函数中获取命名实例

本文关键字:获取 实例 构造函数 StructureMap | 更新日期: 2023-09-27 18:12:17

Main:

class Program
{
    static void Main()
    {
        new CompositionRoot();
        Console.WriteLine("Test");
        var consumer = ObjectFactory.GetInstance<Consumer>();
        consumer.Parse();
        Console.ReadLine();
    }
}

分析器:

public interface IFilePaser
{
    void Parse(string line);
}
public class ITMFileParser : IFilePaser
{
    public void Parse(string line)
    {
        Console.WriteLine("ITM");
    }
}
public class SEQFilePaser : IFilePaser
{
    public void Parse(string line)
    {
        Console.WriteLine("SEQ");
    }
}

成分根:

public class CompositionRoot
{
    public CompositionRoot()
    {
        ObjectFactory.Initialize(x=>x.Scan(scan =>
                                               {
                                                   scan.AssembliesFromApplicationBaseDirectory();
                                                   scan.AddAllTypesOf<IFilePaser>().NameBy(NameBy);
                                               }));
        Consumer.Factory = ObjectFactory.GetNamedInstance<IFilePaser>;
    }

    private static string NameBy(Type type)
    {
        return type.Name.Replace("FileParser", "");
    }
}

消费者:

public class Consumer
{
    public static Func<string, IFilePaser> Factory = name => { throw new NotImplementedException(""); };
    public void Parse()
    {
        Factory("ITM").Parse("");
    }
}

要使用以下重构的Consumer,我必须做些什么?

public class Consumer
{
    private readonly Func<string, IFilePaser> _filePaser;
    public Consumer(Func<string, IFilePaser> filePaser)
    {
        _filePaser = filePaser;
    }
    public void Parse()
    {
        _filePaser("ITM").Parse("");
    }
}

StructureMap:如何在构造函数中获取命名实例

StructureMaps Func<T>技巧未针对命名实例实现。您需要明确注册:

ObjectFactory.Initialize(x => {
   x.Scan(scan => {
      scan.AssembliesFromApplicationBaseDirectory();
      scan.AddAllTypesOf<IFileParser>().NameBy(NameBy);
   });
   x.For<Func<string, IFileParser>>().Use(ObjectFactory.GetNamedInstance<IFileParser>); 
});