具有无参数构造函数的 Ninject 和 Provider 模型

发布于 2024-11-04 03:00:16 字数 415 浏览 1 评论 0原文

我正在实现一个自定义 RoleProvider,并希望使用 Ninject,但是我面临着无参数构造函数问题。关于如何为此注入有任何想法吗?

public class EFRoleProvider:RoleProvider
{
    private readonly IRepository _repository;

    // I want to INJECT this GOO here!
    public EFRoleProvider()
    {
        IContextFactory contextFactory = new DbContextFactory<myEntities>();
        _repository = new RepositoryBase(contextFactory);

    }
}

I am implementing a custom RoleProvider and would like to use Ninject however I am faced with a parameterless constructor issue. Any thoughts on how to inject for this??

public class EFRoleProvider:RoleProvider
{
    private readonly IRepository _repository;

    // I want to INJECT this GOO here!
    public EFRoleProvider()
    {
        IContextFactory contextFactory = new DbContextFactory<myEntities>();
        _repository = new RepositoryBase(contextFactory);

    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

宁愿没拥抱 2024-11-11 03:00:16

您无法注入硬编码的内容。对不起。没有 DI 框架支持这一点。在构造函数中,您已经对实例进行了硬编码,因此这不再是控制反转。为了执行控制反转,您需要尽可能松散地定义层:

public class EFRoleProvider: RoleProvider
{
    private readonly IContextFactory _contextFactory;
    public EFRoleProvider(IContextFactory contextFactory)
    {
        _contextFactory = contextFactory;
    }
}

现在继续配置您的 DI 框架。

You cannot inject something that is hardcoded. Sorry. No DI framework supports this. In your constructor you have hardcoded the instance, so this is no longer inversion of control. In order to perform inversion of control you need to define your layers as loosely coupled as possible:

public class EFRoleProvider: RoleProvider
{
    private readonly IContextFactory _contextFactory;
    public EFRoleProvider(IContextFactory contextFactory)
    {
        _contextFactory = contextFactory;
    }
}

Now go ahead and configure your DI framework.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文