问题描述
我有一个接口类:
public interface IStartUpTask
{
bool IsEnabled { get; }
void Configure();
}
我有多个实现相同接口的类
I have multimple classes implementing the same 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
的类自动绑定到它们自己?
How can i tell Ninject that i want all the classes implementing the IStartUpTask
to bind to themself automatically?
我找到了一个使用StructureMap进行该操作的示例,但是我不知道如何在Ninject中进行操作.
I found an example using StructureMap which does this, but i don't know how to do it in Ninject.
Scan(x => {
x.AssemblyContainingType<IStartUpTask>();
x.AddAllTypesOf<IStartUpTask>();
x.WithDefaultConventions();
});
推荐答案
首先,让我告诉您Ninject将所有类自动绑定到它们自己.您不需要为此做任何特殊的事情.
First of all, let me tell you that Ninject binds all classes to themselves automatically. You do not need to do anything special for that.
话虽如此,我了解如果您想更改范围或附加名称或元数据,则可能需要显式绑定.在这种情况下,请继续阅读.
Having said that, I understand that you might want the explicit binding if you want to change scope or attach names or metadata. In this case read-on.
我不知道是否有可能在香草ninject中做您想要做的事,但是您可以使用 ninject.extensions .惯例.使用该库,您可以编写:
I do not know if it is possible to do what you are after in vanilla ninject, but you can use ninject.extensions.conventions. Using this library you can write:
Kernel.Bind(x =>
x.FromThisAssembly()
.SelectAllClasses()
.InheritedFrom<IStartUpTask>()
.BindToSelf());
这篇关于Ninject绑定实现同一接口的所有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!