主要
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");
}
}
CompositionRoot:
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("");
}
}
如何使用以下重构的消费者?
public class Consumer
{
private readonly Func<string, IFilePaser> _filePaser;
public Consumer(Func<string, IFilePaser> filePaser)
{
_filePaser = filePaser;
}
public void Parse()
{
_filePaser("ITM").Parse("");
}
}
答案 0 :(得分:2)
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>);
});