c# - Ninject:获取服务在我的业务层不起作用

标签 c# dependency-injection ninject ninject.web.mvc

我搜索了很多来解决这个问题,但没有解决方案,我是 DI 和 Ninject 的新手。

我的问题是我可以在 WebUi 层获得我的服务,但我无法在业务层获得我的服务。

此代码在我的 WebUi 中有效,但在我的业务层中无效:

public IValidator<T> GetValidator<T>(T entity)
{
    var d = kernel.Get<IValidator<T>>();
    return d;
}

我在业务层遇到这个错误:

Error activating IValidator{Type} No matching bindings are available, and the type is not self-bindable. Activation path: 1) Request for IValidator{Type}

Suggestions: 1) Ensure that you have defined a binding for IValidator{Type}. 2) If the binding was defined in a module, ensure that the module has been loaded into the kernel. 3) Ensure you have not accidentally created more than one kernel. 4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name. 5) If you are using automatic module loading, ensure the search path and filters are correct.

这是我的代码:

我的界面:

public interface IValidationService
{
    ValidationState Validate<T>(T model);
}

我的具体类:

public class ValidationService : IValidationService
{
    private readonly IKernel kernel;
    public ValidationService(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public ValidationState Validate<T>(T model)
    {
        var validator = kernel.Get<IValidator<T>>();
        if (validator == null) // or just return null?
            throw new Exception(string.Format("No validator found for type                 ({0})", model.GetType()));

        return validator.Validate(model);
    }

}

和我的绑定(bind):

kernel.Bind<IValidationService>().To<ValidationService>();

最佳答案

检查了很久,发现问题了。

我已经这样做了,我的问题消失了:

kernel.Bind<IValidationService>().To<ValidationService>()
            .WithConstructorArgument(typeof(IKernel));

关于c# - Ninject:获取服务在我的业务层不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36715729/

相关文章:

javascript - onclick 事件不工作 asp.net

c# - ASP.NET 蓝屏死机 - 它从哪里获取堆栈跟踪?

c# - ASP.NET EF6 查询模型

c# - 移植到 web api 2 后 NinjectHttpApplication 不起作用

entity-framework-4 - 我的 Ninject 在我的自定义 MembershipProvider 中注入(inject)的 ObjectContext 的范围是什么(使用请求范围)?

c# - 在 asp mvc 4 中将 Json 文本解析为 C# 对象

c# - Unity 记录静态方法 AOP 风格或无接口(interface)

c# - 带类库的 Autofac

java - 工厂返回带有 EJB 注入(inject)字段 Null 的 Bean

asp.net-mvc - 与 Ninject 的集成测试