我认为,如果没有完整的体系结构更改,这可能是不可能的,但我有在运行时为用户公开可配置选项的类(插件)。在类实例化后的运行时使用依赖注入
该程序启动时,用户可以选择使用各种插件,用户面临的选项,他们可以修改为每个插件,用户按下播放按钮,这些配置选项读取和关闭我们去。
当用户选择要使用的插件时,将创建该类的实例,以便它可以显示该插件的可用选项。显然,在正常情况下,当类实例化时,构造函数参数被传入。在这种情况下,如果插件具有ILogger的构造函数参数,并且其具体类具有DirectoryPath的构造函数参数,但只有在用户单击播放后才可读取,我怎样才能获得我的国际奥委会容器通过它?
public class MyPlugin
{
private ILogger Logger;
private Dictionary<string, object> Properties = new Dictionary<string, object>();
public MyPlugin(ILogger Logger)
{
this.Logger = Logger;
SetupProperties();
}
private SetupProperties()
{
Properties.Add("LogDirectory","Please enter a directory");
}
private void UserPressedPlay()
{
//We can now read the property values user has entered
//Now I want to instantiate FileLogger with the LogDirectory property
}
public DoSomething(string Data)
{
this.Logger.Write(Data);
}
}
public interface ILogger
{
void Write(string Data);
}
public FileLogger : ILogger
{
private string DirectoryPath;
public FileLogger(string Directory)
{
this.DirectoryPath = Directory;
}
public Write(string Data)
{
//Write to file
}
}
我目前不使用IOC容器,因此我不会将其作为答案发布,但我认为您想要做的是传入ILogger工厂而不是实际的ILogger。然后可以使用用户的参数从UsrePressedPlay调用工厂以创建实际的Logger实例。 – 2012-03-22 21:01:14
在不改变当前体系结构的情况下,我会在IoC中设置默认构造器设置 - 将设置目录设置为AppData \ Local \ Temp文件夹,然后在用户单击播放后重新初始化Logger界面。 虽然这是相当讨厌的事情,并通过记录器工厂提及500 - 内部服务器错误是一个好主意。 – 2012-03-22 21:14:46
@ 500-InternalServerError所以你主张在这种情况下不使用IOC? – Jon 2012-03-22 21:18:20