Dependency Injection Initialization - c#

Please note: I have just started using AutoFac to learn about DI and IoC.
Is dependency injection supposed to be initialized in the controllers constructor?
How is this?
private IMyService iMyService;
public HomeController(IMyServices myService)
{
iMyService = myService;
}
Different from...
public IMyService iMyService = new MyService();
Lastly, it seems like the dependency still exists.
Edit: Fixed typo, new MyService(); was new IMyService();

Dependency Injection means exactly injection of dependency. It does not say anything about initialization. E.g. if you are injecting dependency which is Singleton, then it can be initialized long before you are injecting it.
Your first code is a usual dependency injection via constructor. Your second code is not dependency injection. Actually it looks odd to me - either you are trying to create instance of interface, which is not possible, or you have bad naming here. If it is just bad naming or typo, then second sample should really look like:
public IMyService iMyService = new MyServiceImplementation();
But you are not injecting anything here. You are simply creating dependency instance (which makes your controller coupled to dependency implementation).

Edit, the dependency always "exists" but it was moved outside of the class
notice that IMyServices can now be defined in the same project as HomeController
when MyService is in totally another class. and your DLL with HomeController can compile without knowing about your MyService dll effectivly decoupling them.
this is a very complex topic and you should read a book about it. reading blogs videos and so on didn;t really help.
this is a good book.
http://www.amazon.com/Dependency-Injection-NET-Mark-Seemann/dp/1935182501
this is a great vidoe lecture series first 5 videos are about DI in general
http://channel9.msdn.com/Blogs/mtaulty/Prism--Silverlight-Part-1-Taking-Sketched-Code-Towards-Unity
initilization is focused in a COMPOSITION ROOT
http://blog.ploeh.dk/2011/07/28/CompositionRoot/
and the pattern you shown here is CONSTRUCTOR INJECTION
https://softwareengineering.stackexchange.com/questions/177649/what-is-constructor-injection

Dependency injection is not trivial - the concept is simple, but understanding it might require some practice and research. Let me give you an example of a place where DI is used, perhaps it will make sense (might not be the best example, sorry I can't think of anything better ATM):
So say you have the following class:
public class MyAwesomeClass {
private readonly IConfig _config;
public MyAwesomeClass(IConfig config) {
_config = config;
}
public IEnumerable<string> GetFiltered() {
IEnumerable<string> results = _config.GetSettings();
// filter my results
return results.Where(x => x.StartsWith("awesome", StringComparison.OrdinalIgnoreCase));
}
}
Now if you're to test GetFiltered you can inject a fake implementation of IConfig and make sure that your filter is working correctly (you isolate your code from depdendencies). You also invert the control by exposing the dependencies and letting the user of your class take care of them, you're pretty much saying - "If you want me to work I need to you to give me an implementation of IConfig, you take care of it."
Here is how the test might look like
[Test]
public void GetsOnlyResultsContainingAwesome() {
var fakeConfig = new FakeConfig();
var awesome = new MyAwesomeClass(fakeConfig);
IEnumerable<string> results = awesome.GetFiltered();
Assert.AreEqual(2, results.Count());
}
Here is the fake implementation of IConfig
public class FakeConfig : IConfig {
public IEnumerable<string> GetSettings() {
return new List<string> { "test1", "test2", "awesome1", "awesome2" };
}
}
I hope this makes sense. Sorry if my example is not good, but I'm just trying to illustrate a point.

You can say that. Actually AutoFac, ninject etc. have feature for binding the interfaces with classes. So you will need to do that first. I mean to say that you will need to create one class and you will need to ask AutoFac and ninject to bind it with the interface.
So, when controller will be looking for any particular interface then AutoFac and ninject will just create object of that class and assign it to interface. And as far as initialization is concerned you can initialize the values while binding the class with interface.

private IMyService iMyService;
public HomeController(IMyServices myService)
{
iMyService = myService;
}
in this case,you only care about what you need(IMyServices)
public IMyService iMyService = new MyService();
but in this case,you care about what it will be(new MyService())
when design a class,you know what you need;
but what it will be,that not decided by you,that decided by who use your class

Related

Is there any practical usage of using unity container to add, resolve dependencies in the controller itself?

In the MVC application i am working with these days, they have registered and resolved all the Interface/Concrete class dependencies inside the controller itself. I read about ioc and dependency inversion and found that the thing that has been done is completely non-useful. Since it would anyway not allow the application to leverage benefits of IoC example mocking, unit testing and would also add cost of adding/resolving the dependencies unnecessarily. Below is code sample:
HomeController
using(IUnityContainer container= new UnityContainer())
{
container.RegisterType<IRepository1, Repository1>()
IRepository1 _repos1 = container.Resolve<IRepository1>();
}
I dont see any point of doing all this stuff if we dont get any benefit out of this. Can someone please tell if this could be of any use now or in future?
If not, i am planning to simply instantiate them with concrete implementations or like:
IRepository1 repos1= new Repository1();
Please ignore the syntax.
(I have editted the code snippet now.)
Using a container to first register and then resolve a concrete type doesn't make any sense, there is no benefit of that. You are still coupled to a concrete type. You could possibly argue that the container helps to match all constructor parameters with instances of respective types but this doesn't count as a real benefit in my opinion.
If you really don't plan to make use of abstractions that are resolved externally, then yes, you can safely remove the bloating container code and create concrete instances, just as you have presented.
The immediate answer to this question is your current implementation causes more overhead and performance impact then doing a standard construction, and you should remove it; or redesign your implementation of Unity.
The following is an example of the benefit of injection that occurs when resolving to a type that has a dependency of another type that is registered with the unity container.
public class UserService
{
internal readonly IRepository _repository;
public UserService(IRepository repository)
{
_repository = repository;
}
//Service Method that exposes 'Domain Logic'
public void CreateUser(string FirstName)
{
_repository.Insert<User>(new User() { FirstName = FirstName }); //Assumes there is a Generic method, Insert<T>, that attaches instances to the underline context.
}
public User GetUser(string FirstName)
{
return _repository.Query<User>().FirstOrDefault(user => user.FirstName == FirstName); // assumes there is a Generic method, Query<T>, that returns IQueryable<T> on IRepository
}
}
register the types (probably in a singleton pattern at Global.asax)
//Resolver is an instance of UnityContainer
Resolver.RegisterType<IRepository, Repository>(new ContainerControlledLifetimeManager());
Resolver.RegisterType<IUserService, UserService>();
Then the logic in your controller is like so:
var service = Resolver.Resolve<IUserService>(); //the resolver will resolve IRepository to an instance as well...
var user = service.GetUser("Grant");

Dependency injection with factory for child class with constructor argument

I've got this app that uses Ninject for DI and I've got the following construction:
public class SomeServicHost
{
private ISomeService service;
public SomeServicHost(ISomeService service)
{
this.service = service;
}
public void DoSomething(int id)
{
// Injected instance
this.service.DoWhatever("Whatever");
// Without injection - this would be how it would be instantiated
var s = new SomeService(new Repo(id));
s.DoWhatever("Whatever");
}
}
interface ISomeService
{
void DoWhatever(string id);
}
class SomeService : ISomeService
{
private IRepo SomeRepo;
public SomeService(IRepo someRepo)
{
this.SomeRepo = someRepo;
}
public void DoWhatever(string id)
{
SomeRepo.DoSomething();
}
}
interface IRepo
{
void DoSomething();
}
class Repo : IRepo
{
private int queueId;
public Repo(int queueId)
{
this.queueId = queueId;
}
public void DoSomething()
{
// Whatever happens
}
So normal injection is not going to work. I'm going to need a factory. So I could do something like:
interface IServiceFactory
{
ISomeService GetService(int id)
{
return new SomeService(new Repo(id));
}
}
Which I acually have already. But if I do that, I lose all of the DI goodness, like lifecycle management, or swap out one implementation with another. Is there a more elegant way of doing this?
Keeping the factory as you describe it, seems fine to me. That's what they are for, when you have services that can only be instantiated at runtime depending on some runtime value (like id in your case), factory is the way to go.
But if I do that, I lose all of the DI goodness, like lifecycle
management, or swap out one implementation with another.
DI is not an alternative for factories. You need both worlds which lead to a flexible, loosely coupled design. Factories are for new-ing up dependencies, they know how to create them, with what configuration and when to dispose them, and if you want to swap implementations, you still change only one place: only this time it's the factory, not your DI configuration.
As a last note, you might be tempted to use the service locator anti-pattern, as proposed in another answer. You'll just end up with worse design, less testable, less clear, possibly tightly coupled with you DI container and so on. Your idea for using a factory is far better. (here are more examples, similar to yours).
Instead of doing
new SomeService(new Repo(id));
you can do
IResolutionRoot.Get<Repo>(new ConstructorArgument("id", id));
IResolutionRoot is the type resolution interface of the kernel, and you can have it constructor injected. This will allow you to benefit from the "DI goodness", as you called it. Please note that you might also want to use the ninject.extensions.contextpreservation extension.
The ninject.extensions.factory, that #Simon Whitehead pointed out already, helps you eliminate boiler plate code and basically does exactly what i've described above.
By moving the IResolutionRoot.Get<> call to another class (.. factory...) you unburden SomeService from the instanciation. the ninject.extension.factory does exactly that. Since the extension does not need an actual implementation, you can even save yourself some unit tests! Furthermore, what about if SomeService is extended and requires some more dependencies, which the DI manages? Well no worries, since you are using the kernel to instanciate the class, it will work automatically, and the IoC will manage your dependencies as it should.
If you wouldn't be using DI to do that instanciation, you might end up with using very little DI at the end.
As #zafeiris.m pointed out this is called Service Locator. And is also often called an anti pattern. Rightly so! Whenever you can achieve a better solution, you should. Here you probably can't. Suffice it to say it's better so stick with the best solution no matter what people call it.
There may be ways to cut down on the usage of service location. For example, if you have a business case, like "UpdateOrder(id)", and the method will create a service for that ID, then another service for that ID, then a logger for that ID,.. you may want to change it to creating an object which takes the ID as inheritable constructor argument and inject the ID-specific services and logger into that object, thus reducing the 3 factory/service locator calls to 1.

Getting an instance of a class that uses dependency injection

I've been reading about dependency injection, and I'm getting the basics. Most of the examples on the internet explain it till here:
public class MyClass
{
private IDependency _dependency;
public MyClass(IDependency dependency)
{
_dependency = dependency;
}
}
This way, we inject the dependency through the constructor. But I don't think it's a good idea to keep writing:
var myClassInstance = new MyClass(someArgument);
all throughout the code. Should I use the factory pattern to get instances?
public static class MyClassFactory
{
private static IDependency dependency = DependencyFactory.GetInstance();
public static MyClass GetInstance()
{
return new MyClass(dependency);
}
}
Is this the way to go?
I know that using a DI container solves the problem, but I'd like to learn how to incorporate dependency injection in my code, before using a DI container.
The dependency injection is just a pattern - you implement it on the first portion of code (constructor injection)
Now you can configure the dependency manually (as you did on the first example) or by using a framework which will help you (behind the scene it will do more or less the same thing).
The value of the pattern is not to avoid writing the below
var myClassInstance = new MyClass(dependencyObject);
but is to decouple layers of software that otherwise would be coupled
Yes, a factory would be the way to go. In fact, a DI container is really just a glorified factory that can be configured via xml (in the case of spring for example) or code (for something like structure map)

What's the best way to create unit tests for services that uses IoC.Resolve()

I'm using an IoC container instead of DI via constructor injection. Some may ask why I'm using IoC containers instead of constructor injection. Well for reasons stated here: Why do I need an IoC container as opposed to straightforward DI code?.
However, I'm finding it difficult to create unit tests for my services. I'm not sure how to mock the repositories used by my services during runtime since I'm not using constructor injection (a conundrum). Anyone have any solutions?
For example:
public class SomeService
{
private ISomeServiceRepository someServiceRepository;
public GetSomeThing()
{
//how do I mock this repository in my unit test
someServiceRepository = IoC.Resolve<ISomeServiceRepository>();
someData = someServiceRepository.getData();
someOtherService = new SomeOtherService();
someThing = someOtherService.GetSomeThing();
return FigureOutSomeThingElse(someData, someThing);
}
public FigureOutSomeThingElse(someData, someThing)
{
//do some figuring
return somethingElse;
}
}
public class SomeOtherService
{
private ISomeServiceRepository someOtherServiceRepository;
public GetSomeThing()
{
//how do I mock this repository in my unit test
someOtherServiceRepository = IoC.Resolve<ISomeOtherServiceRepository>();
var someData = someOtherServiceRepository.getData();
return someData;
}
}
You really should not be using IOC.Resolve inside of your class methods. It is very close to newing up your code anyway, which is part of what you are trying to avoid using DI. A better, and more testable way to write this would be something like this.
Public Class SomeService
{
ISomeServiceRepository someServiceRepository;
public SomeService(ISomeServiceRepository someServiceRepository)
{
this.someServiceRepository = someServiceRepository
}
Public GetSomeThing()
{
someData = someServiceRepository.getData();
...
}
}
By doing it this way, you can just mock your interface and inject it directly.
If you must use .Resolve, then Adam's approach is the best you can do
People can easily launch into a diatribe about how "you're doing it wrong" with resolve as needed, but I have experienced the pain of old code bases that cannot grok the register-resolve-release pattern altruistically. I would, however, advise against using a static container reference (as in IoC.) and try to make the container itself at least injected.
In this situation, you simply provide a test version of the IoC registration container, but instead of the normal app configuration you code a test configuration.
This won't be mocking or stubbing in any true sense and in fact these terms can confuse the solution quite a bit.
In essence it'll just be a different active configuration when in the unit tests. You'll still have to register types manually and you might have difficulty disabling the current configuration code if it is in the execution path of the unit tests.
We have a container that we resolve from as needed in an IoC pattern (for a handful of types), and for testing we simply created a new container (basically, one configuration for code and another for unit tests). Our use case was slightly different in that we injected the container into classes instead of having a static accessible type as in your case.
I got it, this is what I did...
(I'm using Unity.Net & RhinoMock)
Created a baseUnitTest class that implements the IContainerAccessor
Created and initialized a new instance of the UnityContainer in the constructor
Created a "UnityContainer" readonly public property which implements IContainerAccessor.Container
Created a unit test class that inherits baseUnitTest
Added the following code in a test method...
Mocker = New Rhino.Mocks.MockRepository()
SomeRepository = Mocker.DynamicMock(Of ISomeRepository)()
MyBase.UnityContainer.RegisterInstance(Of ISomeRepository)(SomeRepository)
Rhino.Mocks.Expect.Call(Of SomeResult)(SomeRepository.SomeMethod("someArg")).Return(New SomeResult())
Mocker.ReplayAll()
someService = New SomeService()
'this method uses IOC.Resolve(ISomeRepository) and calls the SomeRepository.SomeMethod
someResult = someService.someMethod()
Assert.IsNotNull(someResult)
Done

Having trouble understanding ninject (or just IOC container in general) over factory DI?

Okay, so recently I've been reading into ninject but I am having trouble understanding what makes it better over why they referred do as 'poor man's' DI on the wiki page. The sad thing is I went over all their pages on the wiki and still don't get it =(.
Typically I will wrap my service classes in a factory pattern that handles the DI like so:
public static class SomeTypeServiceFactory
{
public static SomeTypeService GetService()
{
SomeTypeRepository someTypeRepository = new SomeTypeRepository();
return = new SomeTypeService(someTypeRepository);
}
}
Which to me seems a lot like the modules:
public class WarriorModule : NinjectModule {
public override void Load() {
Bind<IWeapon>().To<Sword>();
Bind<Samurai>().ToSelf().InSingletonScope();
}
}
Where each class would have it's associated module and you Bind it's constructor to a concrete implementation. While the ninject code is 1 less line I am just not seeing the advantage, anytime you add/remove constructors or change the implementation of an interface constructor, you'd have to change the module pretty much the same way as you would in the factory no? So not seeing the advantage here.
Then I thought I could come up with a generic convention based factory like so:
public static TServiceClass GetService<TServiceClass>()
where TServiceClass : class
{
TServiceClass serviceClass = null;
string repositoryName = typeof(TServiceClass).ToString().Replace("Service", "Repository");
Type repositoryType = Type.GetType(repositoryName);
if (repositoryType != null)
{
object repository = Activator.CreateInstance(repositoryType);
serviceClass = (TServiceClass)Activator.CreateInstance(typeof (TServiceClass), new[]{repository});
}
return serviceClass;
}
However, this is crappy for 2 reasons: 1) Its tightly dependent on the naming convention, 2) It assumed the repository will never have any constructors (not true) and the service's only constructor will be it's corresponding repo (also not true). I was told "hey this is where you should use an IoC container, it would be great here!" And thus my research began...but I am just not seeing it and am having trouble understanding it...
Is there some way ninject can automatically resolve constructors of a class without a specific declaration such that it would be great to use in my generic factory (I also realize I could just do this manually using reflection but that's a performance hit and ninject says right on their page they don't use reflection).
Enlightment on this issue and/or showing how it could be used in my generic factory would be much appreciated!
EDIT: Answer
So thanks to the explanation below I was ably to fully understand the awesomeness of ninject and my generic factory looks like this:
public static class EntityServiceFactory
{
public static TServiceClass GetService<TServiceClass>()
where TServiceClass : class
{
IKernel kernel = new StandardKernel();
return kernel.Get<TServiceClass>();
}
}
Pretty awesome. Everything is handled automatically since concrete classes have implicit binding.
The benefit of IoC containers grows with the size of the project. For small projects their benefit compared to "Poor Man's DI" like your factory is minimal. Imagine a large project which has thousands of classes and some services are used in many classes. In this case you only have to say once how these services are resolved. In a factory you have to do it again and again for every class.
Example: If you have a service MyService : IMyService and a class A that requires IMyService you have to tell Ninject how it shall resolve these types like in your factory. Here the benefit is minimal. But as soon as you project grows and you add a class B which also depends on IMyService you just have to tell Ninject how to resolve B. Ninject knows already how to get the IMyService. In the factory on the other hand you have to define again how B gets its IMyService.
To take it one step further. You shouldn't define bindings one by one in most cases. Instead use convention based configuration (Ninject.Extension.Conventions). With this you can group classes together (Services, Repositories, Controllers, Presenters, Views, ....) and configure them in the same way. E.g. tell Ninject that all classes which end with Service shall be singletons and publish all their interfaces. That way you have one single configuration and no change is required when you add another service.
Also IoC containers aren't just factories. There is much more. E.g. Lifecycle managment, Interception, ....
kernel.Bind(
x => x.FromThisAssembly()
.SelectAllClasses()
.InNamespace("Services")
.BindToAllInterfaces()
.Configure(b => b.InSingletonScope()));
kernel.Bind(
x => x.FromThisAssembly()
.SelectAllClasses()
.InNamespace("Repositories")
.BindToAllInterfaces());
To be fully analagous your factory code should read:
public static class SomeTypeServiceFactory
{
public static ISomeTypeService GetService()
{
SomeTypeRepository someTypeRepository = new SomeTypeRepository();
// Somewhere in here I need to figure out if i'm in testing mode
// and i have to do this in a scope which is not in the setup of my
// unit tests
return new SomeTypeService(someTypeRepository);
}
private static ISomeTypeService GetServiceForTesting()
{
SomeTypeRepository someTypeRepository = new SomeTypeRepository();
return new SomeTestingTypeService(someTypeRepository);
}
}
And the equilvalent in Ninject would be:
public class WarriorModule : NinjectModule {
public override void Load() {
Bind<ISomeTypeService>().To<SomeTypeService>();
}
}
public class TestingWarriorModule : NinjectModule {
public override void Load() {
Bind<ISomeTypeService>().To<SomeTestingTypeService>();
}
}
Here, you can define the dependencies declaratively, ensuring that the only differences between your testing and production code are contained to the setup phase.
The advantage of an IoC is not that you don't have to change the module each time the interface or constructor changes, it's the fact that you can declare the dependencies declaratively and that you can plug and play different modules for different purposes.

Categories