Getting an instance of a class that uses dependency injection - c#

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)

Related

How to use Dependency Injection with the Facade pattern?

I am using autofac in my UWP application.
I am using the facade pattern for my backend and it is represented by an IFacade interface.
public interface IFacade
{
/* forwards view-models' calls to different parts of the backend */
}
The view-models of my UWP application are using an implementation of IFacade whose concrete implementation is resolved through autofac in the UWP's App instance.
public class App : Application
{
...
private IFacade InitializeDependencies()
{
var containerBuilder = new ContainerBuilder();
// Registers all the platform-specific implementations of services.
containerBuilder.RegisterType<LoggingService>().As<ILoggingService>().SingleInstance();
containerBuilder.RegisterType<SQLitePlatformService>().As<ISQLitePlatformService>().SingleInstance();
containerBuilder.RegisterType<DiskStorageService>().As<IDiskStorageService>().SingleInstance();
containerBuilder.RegisterType<IdentityProviderFactoryService>().As<IIdentityProviderFactoryService>().SingleInstance();
containerBuilder.RegisterType<DefaultVaultService>().As<IVaultService>().SingleInstance();
containerBuilder.RegisterType<LocationService>().As<ILocationService>().SingleInstance();
containerBuilder.RegisterType<NavigationService>().As<INavigationService>().SingleInstance();
// Registers all the dependencies of the Backend project.
var backendDependencies = new Dependencies();
backendDependencies.Setup(containerBuilder);
// Resolves the IFacade.
var container = containerBuilder.Build();
var lifetimeScope = container.BeginLifetimeScope();
return backendDependencies.ResolveFacade(lifetimeScope);
}
I have a lot of services in my backend and my implementation of IFacade ends up with that horrific constructor referencing a lot of services' interfaces, something would make Uncle Bob cringe.
internal sealed Facade : IFacade
{
public Facade(ISessionService sessionService, IEntitiesRepository entitiesRepository, ISynchronizationService synchronizationService, IVaultService vaultService, IIdentityProviderFactoryService identityProviderFactoryService, IDemoTapeService demoTapeService, IDiskStorageService diskStorageService)
{
/* Saves the references as read-only fields. */
}
}
Question
Contrary to the ServiceLocator, using DI forces us to make all the dependencies that are needed visible. I am not sure if I am using the Dependency Injection properly.
What can I do so that my constructor of my Facade class does not have that many parameters?
Solutions tried
Properties
I could change the Facade class and inject the services through public properties. I am not fond of lots of public get / set as my IFacade contract would now indicate that those properties could be changed after the Facade implementation is created, which is not something I want to support (and debug).
Aggregate interfaces
Another option would be to aggregate interfaces together (something that I call the SomethingContext classes) but then it is harder to understand what these groups of interfaces would mean.
Inject a ServiceLocator that is not static in the Facade constructor
The last solution that seems more acceptable (well... acceptable to me) would be to use DI to inject a non-static ServiceLocator. It is kind of solution 2). However, I know the ServiceLocator is something that is frowned upon.
So one another approach is to create some smaller Facade Services and then inject those services to the main facade.
For example you can create such smaller facade for INavigationService and ILocationService:
public class GeographyService : IGeographyService
{
public GeographyService(
INavigationService navigationService,
ILocationService locationService)
{
}
}
The same is true for ISQLitePlatformService and DiskStorageService:
public class StorageService : IStorageService
{
public StorageService(
ISQLitePlatformService databaseService,
DiskStorageService diskStorageService)
{
}
}
That's of course only an example of an idea.
Such an approach is generally considered better than aggregate services with all the dependencies aggregated (http://autofaccn.readthedocs.io/en/latest/advanced/aggregate-services.html) or ServiceLocator (anti-)pattern. You can also read some thoughts about it here: http://blog.ploeh.dk/2010/02/02/RefactoringtoAggregateServices/

Dependency Injection Initialization

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

Ninject / IoC proper initialization of StandardKernel

I'm just getting started with IoC containers and have picked up Ninject to start with. I understand the principle of the separate modules you can incorporate into a Kernel. But I'm curious if I should have the first line below everywhere in my code where I'm about to ask for the concrete implementation of something from my service layer.
IKernel kernel = new StandardKernel(new SimpleModule());
// example: getting my ContentService
IContentService contentService = kernel.Get<IContentService>();
If I have a class with 10 methods that use the ContentService should I really new up a Module and a Kernel in every method? Seems like a code smell. How do most developers handle this with Ninject? Are there any articles online that show the proper way to do this with the consumer class?
If I have a class with 10 methods that use the ContentService should I
really new up a Module and a Kernel in every method?
No, you should have this class take IContentService as constructor parameter (since it depends on it inside its methods) and then ask the kernel to provide you the instance of this class. Your classes should know nothing about the DI container (Ninject in your case). They should never reference it.
There are, basically two ways of working with IoC: Dependency Injection (DI) and Service Location (SL).
When dealing with dependecy injection, you provide you dependencies from outside your classes. Generally, you do this by injecting (passing) your dependencies into the class constructor or by using setters. For example:
public class SomeClass {
public ISomeDependency SomeDependency {get;set;}
public SomeClass(ISomeOtherDependecy someOtherDependency) {
//...
}
}
In this case, you COULD provide a ISomeDependency implementation through the property and you SHOULD provide ISomeOtherDependecy implementation through the constructor. Ninject support both ways.
The other way of doing (SL) allows you to request for your dependencies in the moment you need, for example:
public void DoSomeAction() {
ISomeDependency someDependency = MyServiceLocatorImpl.GetInstance<ISomeDependence>()
}
If you plan to use the SL approach (or an hybrid one), you could use the Common Service Locator (Ninject has support for it) . It makes easy to switch our IoC engine later.

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.

Remove Dependency on IoC Container

After reading more and more about IoC containers, I read this post about not having IoC.Resolve() etc in your code.
I'm really curious to know then, how can I remove the dependency on the container?
I'll want to write code like the following:
public void Action()
{
using(IDataContext dc = IoC.Resolve<IDataContext>())
{
IUserRepository repo = IoC.Resolve<IUserRepository>();
// Do stuff with repo...
}
}
But how can I get rid of the IoC.Resolve calls? Maybe I need a better understanding of DI...
Thanks in advance.
Generally speaking, most dependencies can be injected into your class at the time it is created. However, in this particular case, you need a component that must be created on demand at the time of use. In such cases, it is very difficult to completely remove dependency on an IoC container. My approach has always been to create a factory that is injected into the class at creation time, which in turn encapsulates all direct IoC usage. This allows your factories to be mocked for testing, rather than the IoC container itself...which tends to be a lot easier:
// In Presentation.csproj
class PresentationController
{
public PresentationController(IDataContextFactory dataContextFactory, IRepositoryFactory repositoryFactory)
{
#region .NET 4 Contract
Contract.Requires(dataContextFactory != null);
Contract.Requires(repositoryFactory != null);
#endregion
_dataContextFactory = dataContextFactory;
_repositoryFactory = repositoryFactory;
}
private readonly IDataContextFactory _dataContextFactory;
private readonly IRepositoryFactory _repositoryFactory;
public void Action()
{
using (IDataContext dc = _dataContextFactory.CreateInstance())
{
var repo = _repositoryFactory.CreateUserRepository();
// do stuff with repo...
}
}
}
// In Factories.API.csproj
interface IDataContextFactory
{
IDataContext CreateInstance();
}
interface IRepositoryFactory
{
IUserRepository CreateUserRepository();
IAddressRepository CreateAddressRepository();
// etc.
}
// In Factories.Impl.csproj
class DataContextFactory: IDataContextFactory
{
public IDataContext CreateInstance()
{
var context = IoC.Resolve<IDataContext>();
// Do any common setup or initialization that may be required on 'context'
return context;
}
}
class RepositoryFactory: IRepositoryFactory
{
public IUserRepository CreateUserRepository()
{
var repo = IoC.Resolve<IUserRepository>();
// Do any common setup or initialization that may be required on 'repo'
return repo;
}
public IAddressRepository CreateAddressRepository()
{
var repo = IoC.Resolve<IAddressRepository>();
// Do any common setup or initialization that may be required on 'repo'
return repo;
}
// etc.
}
The benefit of this approach is, while you can not completely eliminate the IoC dependency itself, you can encapsulate it in a single kind of object (a factory), decoupling the bulk of your code from the IoC container. This improves your codes agility in light of, say, switching from one IoC container to another (i.e. Windsor to Ninject).
It should be noted, an interesting consequence of this, is that your factories are usually injected into their dependents by the same IoC framework they use. If you are using Castle Windsor, for example, you would create configuration that tells the IoC container to inject the two factories into your business component when it is created. The business component itself may also have a factory...or, it may simply be injected by the same IoC framework into a higher-level component, etc. etc., ad inf.
One alternative is to re-write the method to accept Func<T> delegates. This removes the dependency from the method and allows you to unit test it with a mock:
public void Action(Func<IDataContext> getDataContext, Func<IUserRepository> getUserRepository)
{
using(IDataContext dc = getDataContext())
{
IUserRepository repo = getUserRepository();
// Do stuff with repo...
}
}
I was on a project a while ago that hadn't settled on an IoC container. They managed the uncertainty by disallowing non-IoC specific features of their container and also by wrapping Resolve with their own class. This is also something I've seen advocated a few times in blog posts... remove the last dependency, the dependency on the dependency injection container.
This is a workable technique, but at some point you have to choose the tools you use and be willing to accept that you'll pay costs to switch to alternative tools. For me, IoC containers fall into the category of things you probably ought to embrace wholeheartedly, so I question this level of factoring. If you want to look into this further, I suggest the following link:
http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion
I blogged about this very issue recently:
How I use IoC Containers
Pulling from the container
Have a second dependency injector to inject the first one, and have the first one inject the second one.

Categories