Main:
class Program
{
static void Main()
{
new CompositionRoot();
Console.WriteLine("Test");
var consumer = ObjectFactory.GetInstance<Consumer>();
consumer.Parse();
Console.ReadLine();
}
}
<>Parsers:
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("");
}
}
我必须做些什么来利用以下重新出版的Consumer?
public class Consumer
{
private readonly Func<string, IFilePaser> _filePaser;
public Consumer(Func<string, IFilePaser> filePaser)
{
_filePaser = filePaser;
}
public void Parse()
{
_filePaser("ITM").Parse("");
}
}