我如何使用Ninject注入依赖关系

我如何使用Ninject注入依赖关系

本文介绍了我如何使用Ninject注入依赖关系,其中实例是从json反序列化的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次尝试使用DI,我选择ninject是因为它据说易于学习,并且有这个问题.

This is my first try using DI, I've chosen ninject for it's reportedly easy learning curve, and have this question.

我正在创建这样的对象:

I'm creating objects like this:

var registrants = JsonConvert.DeserializeObject<List<Registrant>>(input);

我目前有这个Registrant

[Inject]
public Registrant(IMemberRepository memberRepository)
{
    _memberRepository = memberRepository;
}

使用Ninject将存储库依赖项注入反序列化对象的最佳方法是什么?

What is the best way to have the repository dependency be injected into the deserialized object(s) using Ninject?

推荐答案

您不能对非Ninject创建的对象(例如反序列化的对象)使用构造函数注入.但是您可以使用属性注入.只需拨打kernel.Inject(obj)

You can't use constructor injection with objects that are not created by Ninject (e.g. deserialized objects). But you can use property injection. Just call kernel.Inject(obj)

剩下的一个问题是为什么要注入这些对象.通常,您不想在数据容器对象上使用填充注入.在适当的设计中,它们对服务没有任何依赖性.服务上需要完成的操作由数据容器对象的所有者完成.我建议考虑对您的设计进行重构.

One question that remains is why you want to inject those objects. Normally, you don't want to use depedency injection on data container objects. In a proper design they don't have any dependency on services. The operations that need to be done on the services are done by the owner of the data container objects. I recommend to consider a refactoring of your design.

这篇关于我如何使用Ninject注入依赖关系,其中实例是从json反序列化的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:18