This may be stupid question, but I am looking at Ninject sources and don't see NInject registering its own controller factory. I also don't see any IControllerFactory class in Ninject.Web.Mvc assembly. Am I missing something? How does Ninject create controller and inject parameters into constructor?
Lets say we are looking for "/Task/Index".
Ninject MVC applications use now DefaultControllerFactory, the same as non-Ninject applications.
DefaultControllerFactory finds type for controller (TaskController).
DefaultControllerFactory has internal class called DefaultControllerActivator. DefaultControllerActivator has method called Create, which returns controller instance. DefaultControllerFactory asks DefaultControllerActivator for TaskController type instance.
DefaultControllerActivator.Create uses IDependencyResolver. This is where Ninject comes in. Since Ninject implements its own resolver and sets it at the start of application, he gets request for TaskController instance.
The rest is easy. Ninject finds constructor for this type, injects parameters, returns controller instance.
MVC3 now recommends the usage of the IDependencyResolver interface instead of the good old IControllerFactory when dealing with DI. You can look at more details of this interface here.
This is the new Ninject class responsible for injecting the dependencies.
Since controllers are concrete types, Ninject will do self bind. Below is a snippet from ninject.complex.com
Bear in mind that only concrete types can be self-bound; abstract
types and interfaces won't work. Also, if you request an instance of a
type that can be self-bound, and there are no bindings defined for the
type, Ninject will automatically create an implicit self-binding. It's
up to you whether you want to define your bindings explicitly, or let
Ninject figure it out.
If you do need to inject parameters into the constructor. You can create a class inherits from INinjectModule and do the binding there.
Related
This issue is different, I know what DI is, but I want to know how asp.net core use DI. We can configure custom logging in ASP.NET Core, but I do not know why it works.
Normally, we use the new keyword to instantiate a class, and then we can use it in the controller. In ASP.NET Core, we use a controller constructor with parameter like below:
public class HomeController : Controller
{
private readonly ILogger _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
}
I know it is a design pattern called Dependency Injection, but I am wondering how this is implemented. How did the ASP.NET Core team realize this?
In Dependency Injection and Inversion of Control jargon, what is injected is called a "service".
You register your services with an IoC container upon application startup, meaning: you tie concrete implementations and a lifetime to a certain type.
Now when a controller is required to serve an incoming request, MVC will use a controller factory to look up and instantiate the relevant controller. When that controller has constructor parameters, it'll ask the IoC container to resolve the required service parameters.
More information on learn.microsoft.com: Dependency injection into controllers.
I have my project which uses the usual Repository pattern with Services and Unit of Work (all with Ninject injecting the dependencies from a NinjectModule), but I'm trying to access a service from an ActionFilterAttribute to inject some information (from DB) in the layout of the pages I show so I don't need to mess with all the actions on each controller.
The problem comes when I save to DB on one screen and move to the next and then come back to the previous (with a standard #Url.Action): The ActionFilterAttribute for the Index action is triggered but the call to the service and corresponding repository (within the attribute) throw an exception because the DbContext has been disposed.
Is there any problem with accessing a service and, consequently, the DbContext from an ActionFilterAttribute while injecting the service via Property Injection? I want to make a note that I use property injection for the service in the attribute because the constructor receives 2 parameters that are arbitrary depending on the signature of the Action methods, so my only option was to inject via property.
Let me know if you need some code and I'll update the question.
I found the solution to my problem in the following question:
Injecting dependencies into ASP.NET MVC 3 action filters. What's wrong with this approach?
Combining Mark Seeman's answer with striplingwarrior's comment was the solution to it.
Basically I splitted my ActionFilterAttribute into an Attribute that merely decorated my Actions and keeps the parameters I need for later, and also into an ActionFilter that checked the Action's custom attributes and if my attribute exists, then it injects the data I wanted from the DB into the ViewBag. Everything is later binded with the BindFilter extension from Ninject so it applies only to the methods it needs.
I have a HomeController and a Referrence of a type-class.If I create a new object of the class it works fine for me. But I dont want to create new object in the Controller instead I want to pass a referrence of the class through the HomwController's Constructor.Here is my code. I need to implement DI here.
//private readonly UnitOfWork<Student> _unitOfWork = new UnitOfWork<Student>();
private readonly UnitOfWork<Student> _unitOfWork;
//TODO ??
public HomeController(UnitOfWork<Student> unitOfWork)
{
_unitOfWork = unitOfWork;
}
public ActionResult Index()
{
return View(_unitOfWork.GenericRepository.GetAll());
}
Any help?
First, if you want to use dependency injection, you'll have to go through a third party dependency injection container - NInject or Unity for example among many others (or building your own if you are looking for some challenge).
Second, your HomeController should take an abstract unit of work type (interface or abstract class) as a parameter. You are actually using a concrete type in your HomeController constructor which is not how things should work in a dependency injection world (when using "Constructor Injection", your dependency container is in charge of providing the concrete implementation for the abstraction, based on container configuration).
Third your UnitOfWork<Student> does not make a lot of sense. A Repository<Student> would make some sense, but a Unit Of Work is not working on a single "Type" but rather on a "collection" of different data sets (a unit of work is potentially working on a collection of repositories). What would make sense here is to specify a parameter IUnitOfWork unitOfWork in your HomeController constructor, and configure your depency container to pass in a concrete UnitOfWork object on which you can get your Repository<Student> do operations on it in your action method (and potentially on other repositories accessed from the UnitOfWork object) and then Commit all modifcations by calling the associated method on the UnitOfWork object.
You should make some searches arround NInject use with ASP.NET MVC3 and also take a look at EntityFramework if you are dealing with UnitOfWork and Repository patterns (and if data is backed by a DB).
EDIT
In reaction to your comment dealing with (IUnitOfWork<Student> and IUnitOfWork<Course>).
As I said before, it does not make a lot of sense :
A UnitOfWork can be grossly seen as a "container" of repositories, giving access to these repositories and coordinating actions (like commiting all the changes) on these repositories. You should rather have an abstract non generic type IUnitOfWork, providing access to generic repositories such as IRepository<Student> or IRepository<Course>, and also containing a Commit method which would commit to DB (or file, or memory or whatever the unitofwork/repository implementation is targeting to persist data).
This way instead of injecting an IRepository<Student> and/or IRepository<Course> in your controller constructor (or if your controller needs to work on 10 different repositories, well, pass 10 parameters :S), you just accept a single parameter of abstract type IUnitOfWork (the concrete instance being injected by the DI container), and then any action method can work on any set of repository by getting them from the UnitOfWork, and once it has done all the changes, it can call Commit on the unitOfWork which will take care of comming all the modifications that have been done in the repository.
That's the theory and the general idea.
Now more specifically about DI in ASP.NET MVC, the more common way (there are other ways) of "plumbing" the DI container is to create a class inheriting from IDependencyResolver making use of the DI container to resolve types, and in Application_Start call DependencyResolver.SetResolver whith an instance of this class.
This way, when ASP.NET MVC is asked to create a controller (end user request), it will go through this depency resolver to ask for an instance of the controller, and this dependency resolver will turn to the DI container to create an instance of the controller by taking care of all needed injection.
You should take a look on the website / forums of your specific DI container as they all show ways to plumb it with ASP.NET MVC.
This is just a very high overview, there are a lot of tricky details, but that's the gross idea.
EDIT2
Just posted an article (my first one) on my blog to explain how to correctly use the Repository and UnitOfWork patterns in an ASP.NET MVC project.
http://codefizzle.wordpress.com/2012/07/26/correct-use-of-repository-and-unit-of-work-patterns-in-asp-net-mvc/
Are you talking ASP.NET MVC ?
I have been working with Ninject for some time now, and am very happy with it! Take a look at the sample app in this repository to get an idea on how to use it in ASP.NET MVC 3:
https://github.com/ninject/ninject.web.mvc/tree/master/mvc3
To expand a bit on the reply, here's a code snippet from where I set up the Ninject bindings
kernel.Bind(typeof(IUnitOfWork<>).To(typeof(UnitOfWork<>));
And my controller:
public class MyController : Controller {
private readonly IUnitOfWork<Student> uowStudent;
public MyController(IUnitOfWork<Student> uowStudent) {
this.uowStudent = uowStudent;
}
}
Then all you need to do, is make sure any arguments in the constructor for the UnitOfWork class are also bound in the kernel.
I'm trying to implement my custom authorize attribute like:
public class MyCustomAuth : AuthorizeAttribute
{
private readonly IUserService _userService;
public MyCustomAuth(IUserService userService)
{
_userService= userService;
}
... continued
}
I am using Castle Windsor for automatically resolve the dependency.
When I try to use it as an attribute of an action method obviously I am asked to pass the parameter or I need to have a parameter-less constructor that should resolve in some way it's dependency.
I tried to inject the dependency with a property but Windsor is not injecting it.
The only option I see now would be to instantiate manually the concrete object dependency loosing the benefit of Windsor.
How would you solve this problem?
You cannot use DI with attributes - they're metadata;
public class MyCustomAuth : AuthorizeAttribute
{
public void OnAuthorization(...)
{
IUserService userService = ServiceLocator.Current.GetInstance<IUserService>();
}
}
Learn about Windsor/ServiceLocator here.
See similar question here.
You can use a custom ControllerActionInvoker and inject property dependencies (you can't do constructor injection because the framework handles instantiation of attributes). You can see a blog post I just did on this technique.
You did not supply any castle code or configuration examples. Therefore, I am assuming you are new to castle and unfimilar with the registration process.
First of all, any object you want to act upon must come from Castle Windsor via a registered type. With that said, you are going down the wrong path by trying to use castle windsor with attributes - because attributes are not referenced in code, but instead are reflected upon. Therefore, there is not a place for IoC (Castle Windsor in this case) to create the object.
I say this, because what you are trying to accomplish has already been done via different means. First of all, put your dependency injection on your controllers.
public class PostController
{
private IUserService _userService;
public PostController (IUserService userService)
{
_userService = userService;
}
// other logic
}
For Castle to work, you have register all types. So, you have to register IUserService, and what services implement that interface, within Castle Windsor. You can do this via a manual process in your global.asax with container.AddComponentWithLifeStyle; or the more preferred method is to use a configuration file.
Using a configuration file, your IUserService would look something like this:
<?xml version="1.0" encoding="utf-8" ?>
<castle>
<components>
<!--lifestyle="singleton|thread|transient|pooled|webrequest|custom"-->
<component
id="UserService"
service="MyMvcProject.IUserService, MyMvcProject"
type="MyMvcProject.UserService, MyMvcProject"
lifestyle="transient">
</component>
</components>
</castle>
MyMvcProject is the name of your project and make sure to use the exact namespace and fully qualified name of the interface, and type. Please give code samples of your actual namespaces, else we cannot help you any further.
Before that will work, you will need to modify your app.config or web.config to register the searchGroup for Castle Windsor:
<configSections>
<section name="castle"
type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
</configSections>
<castle configSource="castle.config"/>
Now that you are all registered and setup, it is time to tell your MVC application to "Use Castle Windsor to create each instance of my Controllers." Doing this means that Castle Windsor, being an Inversion-of-Control (aka IoC) container, will inspect the dependencies of your controller and see that it depends on IUserService and implement an instance of UserService. Castle will look into its configuration of registered types and see that you have registered a service for IUserService. And, it will see in your configuration file that you want to implement the concrete class of UserService that implements IUserService. So, the IoC container will return UserService when a dependency on IUserService is requested.
But before that can happen, you have to tell your MVC application to use your configuired IoC container. You do this by registering a new ControllerFactory. To do that, see my answer over at this question:
Why is Castle Windsor trying to resolve my 'Content' and 'Scripts' folder as a controller?
And notice the global.asax part of how to register that code. It works quite well!
Now, when all of that is said and done, you want to authorize a user. Use the normal [Authorize] that implements Forms Authentication, and use your _userService to grab any user details of the signed in user.
I'm designing medium-size website using asp.net mvc technology.
All business logic is organized into IServices (like IDomainService, IUserService, IAuthService, ITrainingService). All services are using IRepositories.
I'm using Ninject 1.5 to wire services with controllers and it seems working perfectly.
There is so far one subject I have no idea how to handle. Some services create contexts (per request) - for instance IDomainService creates DomainContext (per request) which is needed for IUserService.
ITrainingService is used only in TrainingController, which is accessible only by authorized users, and ITrainingService requires UserContext (also per request) to know who is having training.
This is my first project using IoC container.
Is there any design pattern or code-schema how to solve it?
I think I can fill context object using ActionFilters but how to manage their lifetime and where to put them to be accessible for IServices? (in an ellegant way)
I've used Ninject specifically in an MVC application. The way you'd accomplish this with Ninject is in the configuration or binding of your dependencies. When you do this, you specify how you want your object lifetimes to be managed. In most cases of a web app, you objects will be per request as you've indicated in your question.
One thing I've noticed in your question is that your DomainContext is being created by an IDomainService object and is used by other objects. If the domain service object is a sort of factory for a DomainContext, then you don't have much of a problem -- this becomes an exercise of how you configure Ninject to provide concrete objects and inject dependencies.
Here's general guidance on how you would structure your application -- bear in mind I don't have full understanding of your interfaces and classes:
public class GlobalApplication : NinjectHttpApplication {
protected override void RegisterRoutes(RouteCollection routes) {
// Your normal route registration goes here ...
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
}
// This function is resposible for creating a Ninject kernel. This is where
// the magic starts to happen.
protected override IKernel CreateKernel() {
var modules = new IModule[] {
new AutoWiringModule(),
new AutoControllerModule(
Assembly.GetExecutingAssembly()),
new ServiceModule()
};
return new StandardKernel(modules);
}
}
Note above that the easiest way to get Ninject to work is to derive your application class from the NinjectHttpApplication class. You will need to change your RegisterRoutes to an override method and will also be required to implement a method called CreateKernel. The CreateKernel method is responsible for returning the Ninject kernel which is itself the IoC container.
In the CreateKernel method, the Ninject-provided AutoControllerModule scans assemblies for MVC controller classes and registers them with the container. What this means is that dependencies on those controllers can now be injected by Ninject as it has become the controller provider for the application. The ServiceModule class is one that you need to create to register all of your services with Ninject. I'm guessing it would look something like this:
internal class ServiceModule : StandardModule {
public override void Load() {
Bind<IDomainService>()
.To<MyDomainService>()
.Using<OnePerRequestBehavior>();
Bind<DomainContext>()
.ToMethod( ctx => ctx.Kernel.Get<IDomainService>().CurrentDomainContext )
.Using<OnePerRequestBehavior>();
Bind<IService>()
.To<MyServiceType>()
.Using<OnePerRequestBehavior>();
}
}
Ninject's got a pretty expressive fluent interface for configuration. Note above that each statement basically associates a concrete class with an interface it implements. The "Using" phrase in the statement indicates to the Ninject kernel that the object will live for the life of the request only. So, for example, this means that anytime an IDomainService object is requested from the Ninject kernel during the same request, the same object will be returned.
As for you context objects, I'm taking a stab that your domain service creates these contexts and acts as a factory of sorts. In that regard, I bound instances DomainContext classes above to be produced by getting the value of the a property called CurrentDomainContext off the IDomainService. That's what the lambda above accomplishes. The nice thing about the "ToMethod" binding in Ninject is that you have access to a Ninject activation context object that allows you to resolve objects using the kernel. That's exactly what we do in order to get the current domain context.
The next steps are to ensure your objects accept dependencies properly. For example, you say that ITrainingService is used only in the TrainingController class. So, in that case I would ensure that TrainingController has a constructor that accepts an ITrainingService parameter. In that constructor, you can save the reference to the ITrainingService in a member variable. As in:
public class TrainingController : Controller {
private readonly ITrainingService trainingService;
public TrainingController(ITrainingService trainingService) {
this.trainingService = trainingService;
}
// ... rest of controller implementation ...
}
Remember that Ninject has already registered all of your controllers with the Ninject kernel, so when this controller is created and it's actions are invoked, you'll have a reference to the ITrainingService by way of the trainingService member variable.
Hope this helps you out. Using IoC containers can become quite confusing at times. Note, I highly recommend you check out the Ninject documentation -- it's a very well written introduction to Ninject as well as DI/IoC concepts. I've also left out discussion of the AutoWiringModule shown above; however, Nate Kohari (Ninject's creator) has a good write-up on his blog about this feature.
Good luck!
Im not exactly sure if I understand your problem completely, hopefully this bit of advice can help.
When using an IoC container you let the container handle object lifetime managment. I have only used Castle Windsor and StructureMap for dependency injection so I cant give you a concrete example for how to do this with Ninject.
Looking through the Ninject documentation I think you want to look at Activation Behaviours to specify object lifetime management.
Hope this helps.