Nancy注册与类型参数

时间:2016-10-24 12:47:13

标签: dependency-injection nancy

Nancy自动注册依赖项无法使用类型参数解析依赖项,因此我尝试手动注册它并且无法弄明白。

public abstract class BaseE { }
public abstract class BaseS<T> where T : BaseE { }
public class E : BaseE { }
public interface ISomething { }
public class S<T> : BaseS<T> where T : BaseE, ISomething { }

我希望ISomething能自动解析为S类,但这不起作用,所以我创建了一个自定义引导程序:

public class CustomBootstrapper : DefaultNancyBootstrapper
{
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ConfigureApplicationContainer(container);
            // Works fine, but not sure if necessary
            container.Register<E, BaseE>();
            // Cannot get the syntax right, doesn't compile
            // ??? container.Register<ISomething, S<E>>();
        }
}

我似乎无法弄清楚语法。第container.Register<ISomething, S<E>>();行给出了编译错误:The type S<E> cannot be used as type parameter 'RegisterImplementation' in the generic type or method 'TinyIoCContainer.Register<RegisterType, RegisterImplementation()'. There is no implicit reference conversion from 'S<E>' to 'ISomething'

请帮我弄清楚使用类型参数注册依赖项的正确语法/正确方法。

1 个答案:

答案 0 :(得分:0)

错误是由于qujck指出的语法不正确。

public class S<T> : BaseS<T> where T : BaseE, ISomething { }

应该是

public class S<T> : BaseS<T>, ISomething where T : BaseE { }

第一种语法说类型T扩展BaseE AND 实现ISomething,第二种语法说类型T只扩展BaseE(而S实现了ISomething)。依赖自动注入现在按预期工作。