Reputation: 9362
I try to access my repository from a class for RSS service. So I used dependency injection for that.
Here is what I do in the NinjectControllerFactory:
ninjectKernel.Bind<IPostRepositoryFactory>().To<NinjectPostRepositoryFactory>().InSingletonScope();
Here is my IPostRepositoryFactory class:
public interface IPostRepositoryFactory
{
IPostRepository GetRepository();
}
public class NinjectPostRepositoryFactory : IPostRepositoryFactory
{
private readonly IKernel kernel;
public NinjectPostRepositoryFactory(IKernel kernel)
{
if (kernel == null)
throw new ArgumentNullException("kernel");
this.kernel = kernel;
}
public IPostRepository GetRepository()
{
return kernel.Get<IPostRepository>();
}
}
Here is the call from my controller:
public ActionResult Feed(int? page = 1)
{
var mgr = new SyndicationManager();
return mgr.GetFeedResult(page);
}
Here is the SyndicationManager class:
public class SyndicationManager
{
[Inject]
public IPostRepositoryFactory m_PostRepositoryFactory { get; set; }
private SiteConfiguration m_SiteConfiguration;
public SyndicationManager()
{
m_SiteConfiguration = SiteManager.CurrentConfiguration;
}
public ActionResult GetFeedResult(int? page = 1)
{
IPostRepository repository = m_PostRepositoryFactory.GetRepository();
var feed = new SyndicationFeed(m_SiteConfiguration.Name,
m_SiteConfiguration.Description,
new Uri(SiteManager.GetBaseUrl()));
So I started debugging from my Feed action controller. Then accessing GetFeedResult and there is the problem: error is that my m_PostRepositoryFactory is always null.
Any help is greatly appreciated.
Upvotes: 3
Views: 417
Reputation: 101192
Why aren't you using constructor injection? It makes it easier to find dependencies of your classes and all resolves will fail directly if any of the dependencies are missing.
Just use the ninject.mvc3
nuget package to configure ASP.NET MVC to use dependency injection for the controllers.
And I don't see the use of a singleton factory to find the repository? Why can't you resolve the repository interface directly?
@Jehof is correct. ninject will not resolve any dependencies when you create objects yourself. But as I said: Don't use the kernel directly, configure MVC3+NInject correctly instead.
http://nuget.org/packages/Ninject.MVC3/2.2.2.0
Upvotes: 1
Reputation: 35554
I´m not an expert on Ninject, but i use Unity as DependencyInjection-Framework. I think the problem is that you instantiate SyndicationManager using its default constructor.
You need to get a reference to the SyndicationManager by resolving it from the Ninject-Kernel, otherwise the dependencies won´t be injected.
public ActionResult Feed(int? page = 1)
{
IKernel kernel = // get the kernel from somewhere
var mgr = kernel.Get<SyndicationManager>();
return mgr.GetFeedResult(page);
}
Upvotes: 1