c# - 使用 TinyIoC 解析带有构造函数参数的具体类型

标签 c# nancy tinyioc

我有一个 Nancy API,并创建了一个继承自 DefaultNancyBootstrapper 的自定义 Bootstraper。

我还有具体类型 ConcreteFoo ,我想在请求范围内将其绑定(bind)到 self 并传递特定的构造函数参数。

public class ConcreteFoo {
    private readonly int _baseInteger;
    public ConcreteFoo(int baseInteger) {
        _baseInteger = baseInteger;
    }
}

我的自定义 Bootstrap 如下:

public class Bootstraper : DefaultNancyBootstrapper {
    protected override void ConfigureApplicationContainer(TinyIoCContainer container) {
        base.ConfigureApplicationContainer(container);
    }

    protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context) {
        base.ConfigureRequestContainer(container, context);
        container.Resolve<ConcreteFoo>(new NamedParameterOverloads {{"baseInteger", 100}});
    }
}

为了使用所需的构造函数参数解析ConcreteFoo,我使用了 TinyIoC Wiki 中提供的示例。 。我注意到代码从我的自定义 Bootstrap 中的覆盖传递,如果我编写以下内容,则响应为true。

var response = container.CanResolve<ConcreteFoo>(new NamedParameterOverloads {{"baseInteger", 100}});

但是,当应用程序引导时,我遇到了异常。下面列出了内部-内部-内部...(很多内部)异常,并指出它无法创建 ConcreteFoo 并且无法解析 System.Int32

InnerException: Nancy.TinyIoc.TinyIoCResolutionException
  HResult=-2146233088
  Message=Unable to resolve type: TestService.Api.ConcreteFoo
  Source=Nancy
  StackTrace:
       at Nancy.TinyIoc.TinyIoCContainer.ConstructType(Type requestedType, Type implementationType, ConstructorInfo constructor, NamedParameterOverloads parameters, ResolveOptions options)
       at Nancy.TinyIoc.TinyIoCContainer.MultiInstanceFactory.GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options)
  InnerException: Nancy.TinyIoc.TinyIoCResolutionException
       HResult=-2146233088
       Message=Unable to resolve type: System.Int32
       Source=Nancy
       StackTrace:
            at Nancy.TinyIoc.TinyIoCContainer.ConstructType(Type requestedType, Type implementationType, ConstructorInfo constructor, NamedParameterOverloads parameters, ResolveOptions options)
            at Nancy.TinyIoc.TinyIoCContainer.ConstructType(Type requestedType, Type implementationType, NamedParameterOverloads parameters, ResolveOptions options)
            at Nancy.TinyIoc.TinyIoCContainer.ResolveInternal(TypeRegistration registration, NamedParameterOverloads parameters, ResolveOptions options)

我找到了this相关问题,但它指的是注册接口(interface)而不是具体类型。

我做错了什么,还是您熟悉另一种解析具体类型并提供构造函数参数的方法?

最佳答案

我认为你需要容器​​。注册...

无论如何,最近我更喜欢使用 IRegistration 类,它是由 Nancy 自动连接的。这样,事情就按主题/关注点分开,并且 Bootstrap 根本不被修改。

关于c# - 使用 TinyIoC 解析带有构造函数参数的具体类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30510496/

相关文章:

c# - 了解 ClientContext.Load 的参数

nancy - 是否有记录 Nancy 服务的自动化方式?

c# - NancyFx 配置请求容器

c# - IOptions 不适用于 TinyIOC/NancyFX

c# - Nancy 使用构造函数参数创建单例

c# - 覆盖 Dictionary<Datetime,int> 的 ContainsKey

C# 在表单退出时中止 (Abort()ing) 线程

C# Web 浏览器控件阻止父级的加载事件

asp.net - Signalr 和 Nancyfx 集成

autofac - 使用 Autofac 进行 NancyFX 功能测试