开发者

How do I Inject Dependencies with Ninject, where instances are deserialised from json

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);

I currently have this constructor for Registrant

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

What 开发者_JAVA技巧is the best way to have the repository dependency be injected into the deserialized object(s) using Ninject?


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.


Assuming you're using Ninject V2, and you're using it in the context of an ASP.NET app, you should be using Ninject.Web to do the hookups.

Then you set up a Global class with the Factory Method support hooked in:

public class Global : NinjectHttpApplication
{
    protected override Ninject.IKernel CreateKernel()
    {
        var kernel = new StandardKernel( new Module() );
        kernel.Components.Add( new FuncModule( ) );
        return kernel;
    }
}

that registers the module that will Bind IMemberRepository to something:

    public class Module : NinjectModule
    {
        public override void Load()
        {
            Bind<IMemberRepository>().To<MemberRepository>();
        }
    }

and the page wires up like this:

public class ThePage : PageBase
{
    readonly Func<Registrant> _createRegistrant;

    public ThePage( Func<Registrant> createRegistrant )
    {
        _createRegistrant = createRegistrant;
    }

    private void OnCreateRegistrant()
    {
        var newRegistrant = _createRegistrant();
    }
}

NB not 100% sure if constructor injection is supported for Web Forms pages or wheter the above needs to drop to property injection... anyone?

(assuming the classes you have are as follows:)

public class MemberRepository : IMemberRepository
{
}

public interface IMemberRepository
{
}

public class Registrant
{
    private readonly IMemberRepository _memberRepository;
    public Registrant( IMemberRepository memberRepository )
    {
        _memberRepository = memberRepository;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜