Cat*_*lin 14 dependency-injection ninject
我有一个接口类:
public interface IStartUpTask
{
bool IsEnabled { get; }
void Configure();
}
Run Code Online (Sandbox Code Playgroud)
我有多个实现相同接口的类
其中一个类看起来像这样:
public class Log4NetStartUpTask : IStartUpTask
{
public bool IsEnabled { get { return true; } }
public void Configure()
{
string log4netConfigFilePath = ConfigurationManager.AppSettings["log4netConfigFilePath"];
if (log4netConfigFilePath == null)
throw new Exception("log4netConfigFilePath configuration is missing");
if (File.Exists(log4netConfigFilePath) == false)
throw new Exception("Log4Net configuration file was not found");
log4net.Config.XmlConfigurator.Configure(
new System.IO.FileInfo(log4netConfigFilePath));
}
}
Run Code Online (Sandbox Code Playgroud)
我如何告诉Ninject我希望所有实现它的类IStartUpTask
自动绑定到自己?
我找到了一个使用StructureMap的例子来做到这一点,但我不知道如何在Ninject中做到这一点.
Scan(x => {
x.AssemblyContainingType<IStartUpTask>();
x.AddAllTypesOf<IStartUpTask>();
x.WithDefaultConventions();
});
Run Code Online (Sandbox Code Playgroud)
And*_*ykh 14
我如何告诉Ninject我希望所有实现IStartUpTask的类自动绑定到自己?
首先,让我告诉你Ninject会自动将所有类绑定到自己.你不需要做任何特别的事情.
话虽如此,我知道如果您想要更改范围或附加名称或元数据,您可能需要显式绑定.在这种情况下,读取.
我不知道是否可以在vanilla ninject中执行您的操作,但您可以使用ninject.extensions.conventions.使用这个库你可以写:
Kernel.Bind(x =>
x.FromThisAssembly()
.SelectAllClasses()
.InheritedFrom<IStartUpTask>()
.BindToSelf());
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9692 次 |
最近记录: |