我有一个接口(interface)类:
public interface IStartUpTask
{
bool IsEnabled { get; }
void Configure();
}
我有多个实现相同接口(interface)的类
其中一个类如下所示:
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));
}
}
我如何告诉 Ninject 我想要所有实现
IStartUpTask
的类自动绑定(bind)到自己?我找到了一个使用 StructureMap 执行此操作的示例,但我不知道如何在 Ninject 中执行此操作。
Scan(x => {
x.AssemblyContainingType<IStartUpTask>();
x.AddAllTypesOf<IStartUpTask>();
x.WithDefaultConventions();
});
最佳答案
How can i tell Ninject that i want all the classes implementing the IStartUpTask to bind to themself automatically?
首先,让我告诉您,Ninject 会自动将所有类绑定(bind)到自身。你不需要为此做任何特别的事情。
话虽如此,我知道如果您想更改范围或附加名称或元数据,您可能需要显式绑定(bind)。在这种情况下,请继续阅读。
我不知道是否可以在 vanilla ninject 中做你想要的,但你可以使用 ninject.extensions.conventions .使用这个库你可以写:
Kernel.Bind(x =>
x.FromThisAssembly()
.SelectAllClasses()
.InheritedFrom<IStartUpTask>()
.BindToSelf());
关于dependency-injection - Ninject 绑定(bind)所有实现相同接口(interface)的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15290353/