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

点点圈 提交于 2019-12-10 07:53:06

问题


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 is the best way to have the repository dependency be injected into the deserialized object(s) using Ninject?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/4988600/how-do-i-inject-dependencies-with-ninject-where-instances-are-deserialised-from

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