Dependency Injection and Moqing - dependency-injection

The way I understand it, DI allows you to use an IoC container to do something like
If a constructor needs an IFoo, use a concrete class Foo : IFoo.
But how is a Mock object using Moq different? Doesn't it also use DI to create a fake Foo?
Thanks.

"Dependency Injection" refers to the general practice of supplying some external resource to an object that requires it. The external resource, or dependency, could be supplied via the object's constructor, a property or method, or even as a method parameter.
And you're right, a common practice is to use an IOC to manage the possible dependencies and supply them to their "clients".
Moq, like other mocking frameworks (or isolation frameworks) is a tool that can be used to generate fake (or stub or mock) objects that can be used as dependencies for the class you're testing. Most mocking frameworks (including, Moq, I think, but I don't use it myself) do not dictate how the fakes are passed to the class under test (TypeMock Isolator is an exception here, in that it has magic that can inject the dependencies into the class under test).
There's no reason why you couldn't use an IOC to register your Moq-created fakes and supply them to your class under test, but that really has nothing to do with Moq (or NMock or Rhino Mocks).

Related

inject service into instance of src/groovy class

I have the following problem:
Under src/groovy I have class that is created in many parts of application (not like spring beans but in the runtime using new () operator)
I want to inject some grails services into all those instances, is it possible somehow without invoking constructor or setters?
Invoking constructors and setters are the only two ways to do dependency injection that I know of. You can use reflection and directly set the field value, but that eliminates any opportunity of having some logic execute when a dependency is injected.
Usually src/groovy (and src/java) classes are called directly or indirectly from an artifact (controller/service/taglib/etc.) that can use dependency injection, so it's often a simple matter of doing the DI there, and passing those Spring beans to the src/groovy classes in their constructors, via setters, or as arguments of the methods that use them.
Obviously if these classes were Spring beans there wouldn't be an issue, because Spring creates them and manages dependencies. But once you are working with a non-bean that has a bean dependency, you either have to do the work yourself, or look into an AOP-style solution, since you need to be notified somehow that there's a new instance that needs to be configured. I assume that this is doable, probably with AspectJ, but it'll probably be more work than it's worth, and add an extra layer of magic to further confuse new team members beyond the regular Grails and Groovy magic.

How to reinject an EF context when using contructor dependency injection with Ninject?

I am injecting all dependencies (services, context) through the contructor with the help of Ninject. The scope of all dependencies is for the current request. Everything works ok but now I want in some case to refresh/reconstruct the Entity Framework context. So basically I just want a dependency reinjected.
I could inject an UnitofWork and call some method on it to remake the context. For Entity Framework this means creating another context. But I am wondering if Ninject will be aware of this and what happens if I further need to use the context in the same request - will it use the old or new context?
To my knowledge ninject does not provide an implementation for what you specifically need.
In your case it might make sense that the client code controls the lifecycle of the ´DbContext´ explicitly. Instead of injecting the ´DbContext´ you would inject an ´IDbContextFactory´. You would need to pass the db context to everyone who will require the same instance.
I've worked on a fairly complicated SW where it was done like this.
However we've gone a step further: As a facilitation, we stored the unit of work (DataContext) in a ´ThreadLocal´. This limits your software in that you can't share the unit of work across multiple threads. However this is usually something you should not do anyway since a transaction should be as short as possible.
The benefit is that then you don't need to pass around the unit of work reference all the time, instead, you create an adapter which you can inject freely and which you use to access the current ThreadLocal's value whenever you need to access the unit of work.
You will still need to explicitly control the lifecycle of the unit of work, though. So you still need the factory which will instanciate the unit of work and assign it to the ´ThreadLocal´. At the end of the unit of work, you commit or rollback and then you reset the ´ThreadLocal´.
Also see this answer which also contains code:
How to use Ninject in a multi-threaded Windows service to get new instances of a dependency (DbContext) on every tick?
Sounds like you either need inject a DbContext factory class, or you could inject a Func< DbContext > and have Ninject resolve this as a method.

Is Dependency Injection a must in asp.net MVC?

I am currently viewing multiple tutorials (and reading books) to start working with ASP.NET MVC.
I see that ninject (or similar) is widely used to implement Dependency injection and from what i understood the main issue here is resource allocation from the classes i need.
We want to be sure for example that we have only one instance of the repo object.
I need to learn first things first so i am interested in knowing how i would create an ASP.NET MVC without using DI techniques and still be correct as far as my object resources are concerned
More info:
I have made some winforms applications. These apps where using a Business Layer DLL (BLL). This BLL had access to my DAL DLL (plain ADO.NET). they are working quite well..
No i want to use the SAME BLL to MVC apps.
With injection or not?
Without injection implementation?
Do i just create the BLL object in my controller constructor and that's all?
ASP.NET MVC doesn't require you to use dependency injection at all. It will work perfectly fine if all of your controllers have default constructors. On the other hand, you will be responsible for creating the objects and managing their lifetimes. If you need to have one repository object for the application, you have to manually implement its lifecycle(using a static variable or Singleton pattern).
If you care about testing, using dependency injection will certainly help you to design more testable and reusable objects. You can easily replace the dependencies with test doubles in your test code and let DI container inject the real implementations in the runtime.
If you are sure about not using it, then make sure all of your controllers have default constructors. You don't need any configuration.
Dependency Injection is not a requirement for using ASP.net MVC. You can definitely build an MVC app without it.
Where it will come in handy is if you want to perform unit testing on your application. If you would like to unit test an action in a controller, if you have DI set up, then you can mock your dependencies that are included in the controller constructor (that DI takes care of when the app is running) and set up responses to return when they are called by the Action.
This is much harder and impractical (if not impossible) to do if you are not using Dependency Injection. In such a case, if you want to use Unit Testing, it will be very hard to write pure unit tests of your Actions, since you will have no easy way to mock your service and data access layers for your tests.
And as you wrote, the DI layer will also enable you to ensure things like having only one instance of the repository objects that you are injecting, etc.

Dependency Injection - Passing dependencies all the way down

I have an MVC application with a typical architecture...
ASP.NET MVC Controller -> Person Service -> Person Repository -> Entity Framework DB Context
I am using Castle Windsor and I can see the benefit of using this along with a ControllerFactory to create controller with the right dependencies. Using this approach the Controller gets a Service injected, which in turn knows how to construct the right Repository, which in turn knows the correct DbContext to use.
The windsor config is something like this...
dicontainer = new WindsorContainer();
dicontainer.Register(Component.For<IPersonService>().ImplementedBy<PersonService>());
dicontainer.Register(
Component.For<IPersonRepository>().UsingFactoryMethod(
() => new PersonRepository(new HrContext("connectionString"))));
It this the right way to do it? I don't like the UsingFactoryMethod, but can't think of another way.
Also, what if the Repository needed a dependency (say ILogger) that was not needed by the service layer? Does this mean I have to pass the ILogger into the service layer and not use it. This seems like a poor design. I'd appreciate some pointers here. I have read loads of articles, but not found a concrete example to verify whether I am doing this right. Thanks.
I try to avoid using factory methods (as you mentioned you felt this smelled funny). To avoid this, you could create a database session object that creates a new DbContext. Then your repositories just need to get an instance of IDbSession and use its dbContext property. Then, you can also easily control the scope of the IDbSession object (don't use singleton because it's not thread safe).
I wanted to make that point so that I could make this more important point... Make your constructors take in only objects that are registered in the DI container (no options or configurations in constructors). Options and configurations should be read/writen in classes whose sole purposes it is to read/write those values. If all classes follow this model, then your DI registration becomes easy and classes can just add whatever dependencies they need in their constructors.
If you are trying to use a third party library that has options in constructors, wrap that class in your own class that has an easy to consume constructor and uses a configuration class to read the values needed to pass to the third party library. This design also introduces a layer of abstraction between your code and the third party library which can then be used to more easily swap (or stub) third party libraries when necessary.

Using a ServiceLocator in Class LIbraries and MVC DependencyResolver

I've really gotten into the DI/IoC things - it makes some things a lot easier. However, I have a few inherited classes that implement a class with a required parameterless constructor, I thus use a service locator to get what I want:
MyMembershipProivder() : MyMembershipProvider(ServiceLocator.Current.GetInstance<...>){}
MyMembershipProivder(IMemberRepo memberRepo){...}
Works perfect. However, since I'm also using MVC3 DependencyResolver I find myself no other way but to do:
var locator = new NinjectServiceLocator(kernel);
DependencyResolver.SetResolver(locator);
ServiceLocator.SetLocatorProvider(() => locator);
DependencyResolver gets used within the MVC app and the ServiceLocator gets used throughout the various class libraries.
Is this the ideal way to do this? Am I missing something?
Update
In the example above, the class is a custom asp.net mebership provider. The asp.net membership provider factory requires for my custom provider to have a parameterless constructor, forcing me to use the service locator to inject the repository that it uses internally.
You don't need the parameterless constructor, the Dependency Resolver will inject your dependency into the constructor:
MyMembershipProivder(IMemberRepo memberRepo){...}
You can replace the default controller factory (to use parameterless constructors in your controllers):
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
You wont need to replace the default controller factory, see Linkgoron's comment below.
Anyway using the Dependency Resolver for your MVC application and the Service Locator for your class libraries is fine, I think.
Hope this helps.
It seems as if you don't really have a choice, unless you can refactor your application to use DI from the start. So, I guess using custom a Service Locator is your best bet.
Although, if the classes you've "inherited" are the controller classes you can just remove the default constructors and be done with it, as MVC will handle everything for you.
I've never seen the ServiceLocator class, is it this?
EDIT:
As I've said, I don't see that you have any other option for decoupling. Service location is probably your best bet, without introducing too much bloat and complexity.
Stuff that's implemented as something built into the .Net FW you should look for specific solutions like the one presented for the Membership Provider.

Resources