使用Unity,如何配置容器,以便在运行时决定第二级依赖项?例如,我有一个类,我通过构造函数注入注入处理器实例。处理器类具有格式化程序和发送方。根据运行时条件,识别格式化程序和发送方,但已注入需要格式化程序和发送方的处理器注入。
考虑以下内容......
模型定义
namespace ClassLibrary1.Models
{
public interface IModel
{
int Id { get; set; }
string Name { get; set; }
}
public class Model : IModel
{
public int Id { get; set; }
public string Name { get; set; }
}
}
发件人定义
using ClassLibrary1.Models;
namespace ClassLibrary1.Senders
{
public interface ISender
{
void Send(IModel Model, string FormattedContent);
}
public class Sender1 : ISender
{
public void Send(IModel Model, string FormattedContent)
{
// do whatever
}
}
public class Sender2 : ISender
{
public void Send(IModel Model, string FormattedContent)
{
// do whatever
}
}
}
格式化程序定义
using ClassLibrary1.Models;
namespace ClassLibrary1.Formatters
{
public interface IFormatter
{
string Format(IModel Model);
}
public class FormatterA : IFormatter
{
public string Format(Models.IModel Model)
{
return "aaaaaaaaa";
}
}
public class FormatterB : IFormatter
{
public string Format(Models.IModel Model)
{
return "bbbbbbbbb";
}
}
}
处理器定义
using ClassLibrary1.Formatters;
using ClassLibrary1.Models;
using ClassLibrary1.Senders;
namespace ClassLibrary1.Processors
{
public interface IProcessor
{
string Process(int Id);
}
public class Processor : IProcessor
{
private IFormatter formatter;
private ISender sender;
public Processor(IFormatter formatter, ISender sender)
{
this.formatter = formatter;
this.sender = sender;
}
public string Process(int Id)
{
IModel model = new Model() {Id = Id, Name = "test"};
var formattedText = this.formatter.Format(model);
this.sender.Send(model, formattedText);
return formattedText;
}
}
}
最后消费者......
using ClassLibrary1.Processors;
namespace ClassLibrary1
{
public class Test
{
private IProcessor processor;
public Test(IProcessor processor)
{
this.processor = processor;
}
public void MyMethod()
{
// IF DAY OF THE WEEK IS MONDAY, THEN RESOLVE SENDER TO SENDER1 AND FORMATTER TO FORMATTERA
// IF DAY OF THE WEEK IS TUESDAY, THEN RESOLVE SENDER TO SENDER1 AND FORMATTER TO FORMATTERB
// IF DAY OF THE WEEK IS WEDNESDAY, THEN RESOLVE SENDER TO SENDER2 AND FORMATTER TO FORMATTERA
// IF DAY OF THE WEEK IS THURSDAY, THEN RESOLVE SENDER TO SENDER2 AND FORMATTER TO FORMATTERB
this.processor.Process(123);
}
}
}
答案 0 :(得分:1)
我不认为这是你可以要求团结去做的事情。我会使用某种工厂来做逻辑来返回正确的格式化程序和发送者。然后可以将此工厂注入您的处理器类。
public interface IFormatter
{
string Format(Model model);
}
public interface IFormatterA : IFormatter
{
}
public interface IFormatterB : IFormatter
{
}
public interface IFormatterFactory
{
IFormatter Create();
}
public class FormatterFactory : IFormatterFactory
{
private IUnityContainer _container;
public FormatterFactory(IUnityContainer container)
{
_container = container;
}
public IFormatter Create()
{
if (Monday)
return _container.Resolve<IFormatterA>();
if(Tuesday)
return _container.Resolve<IFormatterB>();
}
}