与其他,非依赖,构造函数参数的构造函数注入 [英] Constructor injection with other, non-dependency, constructor arguments

查看:186
本文介绍了与其他,非依赖,构造函数参数的构造函数注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是IOC容器的新手,我开始使用NInject。

I'm new to IOC containers, and I'm getting started with NInject.

如果你想让你的构造函数有参数不是服务,而不需要由IOC容器实例化。

What do you do if you want your constructor to have parameters that are not services and don't need to be instantiated by the IOC container?

例如:

public class Person
{
    private readonly string _name;
    private readonly IPersonRepository _repository;

    public Person(string name, IPersonRepository repository)
    {
        _name = name;
        _repository = repository;
    }

    ......
}

想象一下,名称是Person类的要求,因此,为了确保一个Person总是有一个名称,我们需要将它传递给构造函数。

Imagine that name is a requirement of the Person class, so, to ensure that a Person always has a name, we require that it be passed in to the constructor.

我们如何使用NInject获取Person的实例?该名称需要通过应用程序的任何一个位创建一个新的人,而IOC容器需要传递IPersonRepository。

How would we get an instance of Person using NInject? The name needs to be passed in by whichever bit of the app is creating a new Person, whilst the IOC container needs to pass in the IPersonRepository.

我理解,名称或存储库可以使用属性注入,但这不会是一个干净的解决方案 - 我们失去了一些编程语言的语义能力。

I understand that either the name or the repository could be injected using a property instead, but this would not be a clean solution - we are losing some of the programming language's semantic power.

推荐答案

如上所述,类不适合与IOC容器一起使用。你在这里混合关注Person实体持有一些状态(名称)和执行一些操作(无论使用的存储库)。如果你重构你的代码,以便Person实体被检索或创建一个类,通过构造函数接受IPersonRepository的实现,那么你会在依赖注入更有意义的地方。

The class, as written above, wouldn't be a good candidate for use with an IOC container. You are mixing concerns here with the Person entity holding some state (the name) and performing some action (whatever the repository is used for). If you refactor your code so that the Person entity is retrieved or created via a class that takes an implementation of the IPersonRepository via the constructor then you'll be in a spot where the dependency injection makes better sense.

这篇关于与其他,非依赖,构造函数参数的构造函数注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆