I have an ASP.NET MVC5 web site that uses Ninject. The site is for an online magazine.
What I would like to do is set up some routes, but pull the data from an injected repository. So, I would like to have routes like these...
routes.MapRoute("Section9", "Section9_Ask-the-professional",
new {controller = "Sections", action = "Detail", id = 9});
routes.MapRoute("Section10", "Section10_Confrontation",
new {controller = "Sections", action = "Detail", id = 10});
...where the section IDs (9 and 10 in the sample above) and the section names are pulled from the repository.
Can I access an injected repository in RouteConfig.RegisterRoutes()? I tried adding the usual code...
[Inject]
public SectionsRepository<Section> Repository { get; set; }
...but this didn't work, as the repository was always null. I tried making it static, but no joy.
Anyone any ideas? I've spent quite a bit of time searching, but not found anything, mainly due to the noise from results about routing or injection in general.
If I get you right, you want to have access to your repository to assign Article names to your urls. It can be done, but first, think about what you've just wrote here:
The
[Inject]
attribute tells the framework that any property decorated by this attribute should be assigned a value to by Ninject. Do you instantiate your RouteConfig class with Ninject? No, you don't, (especially asRegisterRoutes(...)
is static so it won't have access to instance-level data anyway) therefore you don't configure Ninject to do anything with it. So your property will obviously be null, because Ninject won't touch your RouteConfig class.The solution: Add this
line of code into your RouteConfig class whereever you feel it makes sense, like as a default assigned value, or into the RegisterRoutes(...) method, like this:
To access your DI implementation here, you obviously have to set your resolver before calling
RouteConfig.RegisterRoutes(RouteTable.Routes);
in your Global.asax file, like this:Hope this helps.