Can't figure out how to get this DI stuff going
Ok, I feel like a total idiot. I have read the docs and still cant get this working with Ninject.
public class ContextAdapter:IDbSetProvider
{
private readonly IContextFactory _contextFactory;
#region Implementation of IDbSetProvider
public ContextAdapter(IContextFactory contextFactory)
{
this._contextFactory = contextFactory;
}
public IDbSet<TEntity> CreateDBSet<TEntity&g开发者_如何学编程t;() where TEntity : class
{
var context = _contextFactory.Create();
return context.Set<TEntity>();
}
#endregion
}
As you can see I am need to inject the contructor for the class above. Well, it is not going so well. Help!! before I go back to writing perl code. Kidding!! LOl
Thoughts folks?
Your class ContextAdapter
does not implement IContextFactory
. Do you have a class like class Factory : IContextFactory
? That is what you are missing here. Then you can bind it kernel.Bind<IContextFactory>.To<Factory>()
and Ninject will create that type for you when you request an object or when it needs to fulfill a contract. I think your confusion comes from the binding syntax. You are, in general, not binding parameters together, you are binding interfaces to concrete implementations. Here is a quick example:
Bind<IEngine>.To<GasEngine>();
Bind<ICar>.To<Sedan>();
class Sedan : ICar
{
public Sedan(IEngine engine) { }
}
// ...
kernel.Get<ICar>(); // get me a new car
When you ask Ninject for ICar
, it will fulfill it with what was bound, Sedan
. Sedan
requires an IEngine
in its constructor, which Ninject will fulfill with GasEngine
since that is what was bound.
精彩评论