Constructor injection with other, non-dependency, constructor arguments

偶尔善良 提交于 2019-12-05 01:49:50

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.

Its been more than a year since I asked this question, and I know more now than I did back then. Kevin's answer is correct and best practice, but sometimes you need to work with legacy classes and want to do something like I have in my question. Here's how I do it with NInject:

public class Person
{
    [Inject]
    public IPersonRepository PersonRepository { get; set; }

    private string _name;

    public Person(string name)
    {
         _name = name;
         StaticKernelContainer.Inject(this);
    }
}

An implementation of StaticKernelContainer can be found in the NInject Web extensions project.

I respectfully disagree with Kevin McMahon's response above, and the reason is that I have seen dependency injection code that does exactly what you want ... only with a different IoC container. Namely, it was Castle Windsor, which is another Ioc container. It would allow you to create a section in your config file to say what values to provide for name (doesn't make much sense to do that for name, but if it was a property like "connectionString", it might make a lot of sense).

So ... it's not that what you are trying to do is not a fit for dependency injection in general ... it's just that Ninject doesn't seem comfortable with it (or perhaps Ninject can accommodate it as well ... I don't know all of its lesser used features well enough to say).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!