dependency-injection - 带有 funq 的 servicestack - 按照惯例 Autowiring

标签 dependency-injection inversion-of-control servicestack convention-over-configur funq

我有一个在其构造函数中采用 IMyDependency 的服务。 IMyDependency、MyDependency 和服务都存在于同一个程序集中。 MyDependency 有一个单一的、公共(public)的、无参数的构造函数。

令我惊讶的是,这不起作用:

container.RegisterAutoWired<IMyDependency>();

它抛出一个“System.NullReferenceException”。

如果我这样做,它会起作用:
container.RegisterAutoWiredAs<MyDependency, IMyDependency>();

但是,这样做也是如此:
container.RegisterAs<MyDependency, IMyDependency>();

那么区别是什么呢?如果“自动布线”找不到具体的实现,而需要依赖的服务能否解决也无所谓,那什么是自动布线呢?

Funq 是否应该能够按照惯例找到您的具体实现?如果是这样,该约定是什么,如果不是同名?

谢谢。

最佳答案

您的意思是“我如何实现一个解决方案来搜索程序集并根据约定在 ServiceStack IOC 中自动注册类?”

如果是这样,我可能会为您提供解决方案:

  • 创建一个您的可注入(inject)类将实现的接口(interface)。
  • 让您的可注入(inject)类实现该接口(interface)。
  • 在引导代码中,使用反射来搜索您的程序集并获取所有实现可注入(inject)接口(interface)的类的列表。
  • 使用反射根据您的约定获取类名和接口(interface)。
  • 调用ServiceStack IOC方法 RegisterAutoWiredType 并传入类和接口(interface)来注册它们。

  • 例如,如果我们的命名约定是 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();
        }
    }
    

    关于dependency-injection - 带有 funq 的 servicestack - 按照惯例 Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16226798/

    相关文章:

    c# - 在 ASP.NET Core 中初始化依赖注入(inject)时传递参数

    java - 我可以确保我的 Spring ApplicationListener 之一最后执行吗?

    scala-将自类型注释类传递给子对象

    servicestack - 需要 HTTP header 的 REST 服务的推荐模式?

    c# - 将开放泛型与 Funq 结合使用

    c# - ASP.Net MVC 6 中的依赖注入(inject) (DI)

    java - 如何在 servlet(或任何其他 Java 类)中使用 @Resource 注释?

    c# - 使用 UnityContainer 进行动态 IOC 映射 - 如何实现?

    c# - IOC 容器的最佳实践

    servicestack - 我绕过了 servicestack 来实现我自己的 IHTTPHandler,但现在我想访问缓存