我有一个在其构造函数中采用 IMyDependency 的服务。 IMyDependency、MyDependency 和服务都位于同一个程序集中。 MyDependency 有一个单一的、公共的、无参数的构造函数。
令我惊讶的是,这不起作用:
container.RegisterAutoWired<IMyDependency>();
它抛出“System.NullReferenceException”。
如果我这样做,它会起作用:
container.RegisterAutoWiredAs<MyDependency, IMyDependency>();
但是,这也是如此:
container.RegisterAs<MyDependency, IMyDependency>();
那么区别是什么呢?如果“自动装配”找不到具体的实现,并且对于需要依赖的服务能否解决也没有影响,那么什么是自动装配呢?
Funq 应该能够按照约定找到您的具体实现吗?如果是这样,如果不是同名,那么该约定是什么?
Thanks.
您的意思是“如何实现一个解决方案来搜索程序集并根据约定自动在 ServiceStack IOC 中注册类?”
如果是这样,我可能会给你一个解决方案:
- 创建一个可注入类将实现的接口。
- 让您的可注入类实现该接口。
- 在引导代码中,使用反射来搜索程序集并获取实现可注入接口的所有类的列表。
- 使用反射根据您的约定获取类名和接口。
- 调用ServiceStack IOC方法注册自动连线类型并传入类和接口来注册它们。
例如,如果我们的命名约定是 ClassName IClassName:
private static void RegisterCustomTypes(Container container)
{
//Get the Assembly Where the injectable classes are located.
var assembly = Assembly.GetAssembly(typeof(IInjectable));
//Get the injectable classes
var types =assembly.GetTypes()
.Where(m => m.IsClass && m.GetInterface("IInjectable") != null);
//loop through the injectable classes
foreach (var theType in types)
{
//set up the naming convention
var className = theType.Name;
var interfaceName = string.Concat("I", className);
//create the interface based on the naming convention
var theInterface = theType.GetInterface(interfaceName);
//register the type with the convention
container.RegisterAutoWiredType(theType, theInterface);
}
}
public interface IInjectable
{
}
//This class can be injected
public interface ITestManager : IInjectable
{
void Execute(int id);
}
public class TestManager : ITestManager
{
public void Execute(int id)
{
throw new System.NotImplementedException();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)