I want to make my architecture better but i don't know how to resolve dependency trouble.
What i have:
class library CoreService witch have a lot of interfaces IMail, Ilog, ISession
In app start i created IMail, Ilog, ISession based classes and pass it to CoreService class
base controller class with CoreService instance (property CoreService Services {get;})
user plugin use CoreService interfaces
The problem:
Every time i need to add new service i must edit app start, CoreService. Ideally I would like just create a class lib for IMail (or any other service) and register it in web.config or in app start.
I would appreciate for any advice or links that will help me.
Thanks for all so users!
Take a look at Ninject and XML configuration Binding.
I think this covers both parts of what you're aiming to achieve. This is dependency injection as well as being able to modify configuration without needing to recompile.
If you add entirely new services that Ninject (or other DI containers - Unity for example) isn't resolving for you, you will need to edit your code. I don't think that's avoidable.
What you need is a Dependency Injection framework to resolve your dependencies. DI frameworks will manage the creation and lifetime and disposing of objects.
builder.RegisterType<MySession>().As<ISession>().InstancePerHttpRequest();
builder.RegisterType<MyMail>().As<IMail>().Singleton();
Then you can use constructor injection to inject these
public class MyController : BaseController
{
public MyController(ISession session, IMail mail)
{
_session = session;
_mail = mail;
}
//other methods and member variables
}
This way you have to modify only one place when you need to add new dependencies.
Related
here's an example of what i am talking about
public interface IService<T>
where T : class
{
List<T> GetAll();
T GetById(object id);
.......... other methods here
}
public class Service<T> : IService<T>
where T : class
{
... implement interface here
}
public class ServiceClient
{
private readonly IService<User> _service;
public ServiceClient(IService<User> service)
{
_service = service;
}
public ServiceClient() : this(new Service<User>()){}
}
can someone tell me the difference between this and a Dependency Resolver? I normally Use SimpleInjector for Dependency Injection, I just want to know the benefits of the Container over doing the above..
Thanks
Update
okay lets say I have setup my Containers now and removed the 'this' constructor initialization, I Want to now Test ServiceClient
Let use MS unit test for snippet
[TestMethod]
public void Given_Something_Should_Success()
{
// Arrange
// how do i make an instance of this in a test without adding the 'new Service<User>()' part
ServiceClient client = new ServiceClient(new Service<User>());
}
and without changing my ServiceClient constructor to do this. Is it even possible to do that at this level? Sorry if this is a noob question i'm just trying to understand some things about it.
public ServiceClient(IService<User> service = null)
{
_service = service ?? new Service<User>();
}
See this line of code:
public ServiceClient() : this(new Service<User>()){}
Now the ServiceClient is aware of Service<User> class and the assembly where the ServiceClient is will not build without having a reference to the assembly where Service<User> class is located. Furthermore, if Service<User> has additional methods which are not in IServiceUser<User>, then the developer may do this within the class:
(this._service as Service<User>).SomeMethodNotBelongingToTheInterface();
Now one can argue that an irresponsible developer will do that sort of thing, but that is beyond the point here.
To be totally decoupled from the concrete implementations, you should never call new and leave this to the Composition Root. Both your classes and your assembly should only work with the interfaces and be totally unaware of the concrete implementations. This guarantees that you can plug any implementation at the composition root level, and everything will work.
This does not mean that even POCO classes without behavior should be behind interfaces but just classes that require plug and play sort of behavior.
If you follow this pattern, you can also create architectural diagrams within Visual Studio and instruct which layer can have references to which assemblies. During build, the build will fail (if configured to fail) if the developer creates a reference to an assembly they are not allowed to reference.
At the composition root level, it is up to you whether you want to plug the classes into each other using an IoC container or doing it manually. But why do it manually if there are good tools (IoC containers) which can do this for you. You can have one config file where all the test classes are and another where the real classes are. You can instruct your whole program to run with either configuration with just one line of code: This is what I mean by plug and play. The whole idea behind dependency injection, loose coupling etc. is that your classes should not have code which is written against a concrete implementation.
In Container you would register your class and interface.
Benefits are , you have one ioc class which will take care of providing you right type.
So you can program against interface.
and you do not need to new up in your code.
this gives you also flexibility when you have to manage scope or mock some class.
Here is some example how you register via IoC (Autofac)
builder.RegisterInstance(new ServiceClient())
.As<IService>();
What using a Container gives you is a centralised place in your application to specify how your dependencies should be resolved.
Imagine you have many classes that wants to inject the same implementation of IService. By using your approach above, you would have to write that same code for all of those classes. If you would have used a container, specifying it there would be enough.
Also, many DIs gives you more functionality for sharing instances, maintaining life cycles of your injections etc, provide dependencies to your dependencies etc.
This is called Bastard injection and you shouldn't do this because is totally against the purpose of dependency inversion: to create decoupled and maintainable code. If you use a default implementation it means that you have to reference the project that contains the implementation of your service. Or worst you probably create the implementation of your service in the same library where it lives the interface.
On the other hand you might have a good default implementation. For example you might define this interface:
public interface IClock
{
DateTime Now { get; }
}
The obvious implementation of this interface is
public class Clock : IClock
{
public DateTime Now => DateTime.Now;
}
I wouldn't use though a public constructor for this, I would inject it via a Property and leave the constructor for another implementation (maybe a mock from your tests). Also SimpleInjector I think would shout about having two constructors. It is a tool which made me to read more about these ideas.
When the IService's implementation is something that talks with a database, or HTTP service, or a remote one, or with 3rd party library or with file system, then these are good reasons for you create a separate project, reference the one you defined the interface, create the implementation, then in your place where you setup the simple injector, you can bind the interface with the implementation (which requires here to reference both projects). If on a later time you need a diferent implementation you can simply repeat the process and change the composition root.
I'm trying to get more and more familliar with DI and IoC. At this moment I understand the concept and implementation of DI with the controllers in an MVC application. But assume I have a layered application.
The Controllers call businesslogic classes and the businesslogic clases call the repository classes.
How do I setup the second layer, the businesslogic to repository part with DI. This ensures I can test on different levels in my application. What I don't want to do is passing the dependancy to the repository from the controllers.
Hope someone can give some hints on this.
Patrick
Minimalistic example how to implement using Ninject. This is not absolute truth about DI/IoC, just a brief example how it could be done.
Configuration
// repositories
base.Bind<IMyRepository>().To<MyRepository>();
// services
base.Bind<IMyServices>().To<MyServices>();
When ever IMyRepository is used then it will use concrete implementation MyRepository.
Controller
public class MyController : Controller
{
private readonly IMyServices _myServices;
public AnimalController(IMyServices myServices)
{
_myServices = myServices;
}
// your actions
}
Again, inside MyService there is a similar pattern (constructor injection)
Service
public class MyServices : IMyServices
{
private readonly IMyRepository _myRepository;
public MyServices(IMyRepository myRepository)
{
_myRepository = myRepository;
}
public void Example()
{
_myRepository.PleaseDoSomething();
}
}
Also remember that there are lots of other things in the ASP.NET MVC where IoC can be used:
localization
authorization
model metadata provider (for example localized error messages)
custom model binders
controller factory
etc.
Update
In the example code there was a bug. Dependency injection was not done in the service. Now it should be correct.
Update 2
I think it's highly recommended to use NuGet packages to bootstrap your app. Saves time, might apply some "best practices", other projects will get similar base etc. Here are some instructions for different IoC's + MVC 3
Ninject
Autofac
StructureMap
put simply, each layer in the hierarchy asks for the dependencies on the next layer down via a constructor argument, which is an interface.
your controllers ask for their dependencies on a business logic through their constructors. They do this by a dependency on an interface to the business logic not by asking for a particular implementation. You create an interface for your business logic class, and inject an implementation of that interface into your controller, this can be done manually or you can get a DI container to do it for you. Your controller knows nothing about the repository classes (or any other dependencies of any implementation of the business logic), only about the interface to the business logic class on which it depends.
You then rinse and repeat on the business logic concrete classes.
You create an interface for your repository classes and the business logic classes which require those ask for them through their constructor, and then you again inject the dependency in either manually or via a DI container.
You application should have a composition root where all of this setup takes place, which is where you either manually wire up your dependencies (create the lowest objects first and then pass them in to the constructors of the higher up objects as you create those), or you configure the container with the details of the implementation of various interfaces you have, so that it can then use that information to correctly construct objects which have dependencies.
A DI container just creates and resolves dependencies for types it's configured to. It is unrelated to how do you design your application layers. Why don't you want to pass the repository where it's needed?! Those objects depend on an abstraction and not on implementation.
You configure the DI container to serve a certain instance of Repository anywhere where it's required. The controller receives the repository instance, which then can be passed on to the business layer to be used.
Decoupling means an object doesn't depend on implementation details, that's it. Testing is possible because the dependecies are expressed as interfaces and you can mock them.
I am aware that a thousand and one questions relating to this topic have been asked, but I have gone through at least a dozen and am still not connecting the dots. I am trying to setup dependency injection for entity contexts.
I have always created my entity context as I have seen in the MS tutorials, like so:
public class UserController : Controller
{
private DbEntities db = new DbEntities();
}
Recent reading has told me that this is no longer (if it ever was) the best practice, and a dependency injection method should be used. Ninject is mentioned often, but I am seeing how you move from what I have, to the example give in the Ninject documentation.
It should look like this when I am done, right?
public class UserController : Controller
{
private DbEntities db;
public UserController(DbEntities context)
{
db = context;
}
}
The documentation starts out with "In the previous step we already prepared anything that is necessary for controller injection." which is confusing as hell, since the previous step was installation. I used the Nuget method to install, but I don't know what it means when it says "Now load your modules or define bindings in RegisterServices method." How do I do that, and is entity a module or a binding? The documentation feels so sparse.
I am sorry if I skipped over something critical in the docs, I've been bouncing between forums for hours trying to figure out this one step.
I used the Nuget method to install, but I don't know what it means
when it says "Now load your modules or define bindings in
RegisterServices method." How do I do that, and is entity a module or
a binding?
The Nuget installation actually does quite a lot of things for you already. The most important thing is that it sets up Ninject as controller factory, which means that Ninject will create your controllers and is able to pass in all dependencies you have registered with it.
If you check the App_Start folder you will find a file NinjectMVC3.cs. There is already an empty method RegisterServices() which you can use to register your dependencies.
For your example you must be able to resolve DbEntities. The easiest most basic way to do this is:
kernel.Bind<DbEntities>().ToSelf();
That said you really should pass in an interface to your controller so the controller does not depend on Entity Framework, using abstractions and registering a concrete class to use in the IoC container is one of the main reasons for dependency injection.
This should give you a start - the documentation you link to seems a bit outdated. I would recommend looking at the Ninject MVC3 sample on github.
Dependency Injection can seem confusing at first, but it's really actually quite simple.
A Dependency Injection "container" is basically a generic factory, with various object lifetime management features. Ninject, in particular, uses the syntax kernel.Bind() to confgure this factory. When you say kernel.Bind<DbEntities>().ToSelf() this means that Ninject will create an instance of the bound type (DbEntities in this case) whenever that type is requested. This request typically looks like this:
var entities = kernel.Get<DbEntities>(); // Note: don't do this, just an example
At it's core, this is what Dependency Injection is. A generic factory that can instantiate arbitrary types.
However, there is a lot more to it than that. One nice feature of Dependency Injection is that it will also instantiate any dependent types in the process. So, suppose you have a controller, and that controller has a dependency on DbEntities. Well, when a controller is instantiated by the DI Framework, it will also instantiate the dependent DbEntities. See the code below. When the MyController is instantiated, the DbEntities will automatically get instantiated (assuming you have bound the DbEntities class to self in the DI Configuration)
var controller = kernel.Get<MyController>();
public class MyController : Controller {
private DbEntities _entities;
public MyController(DbEntities entities) {
_entities = entities;
}
}
This is recursive. Any class that gets instantiated that has any objects that it itself might depend on get instantiated as well, and so on, and so on until finally, everything has what it needs to do its job.
Now, the great thing about MVC is that it has a way built-in to use any DI container automatically. You don't have to call kernel.Get because the framework does it for you when it creates the controllers when a request comes in. This feature is called IDependencyResolver, and is an interface that the MVC framework uses to allow third party DI containers to be used by the framework.
If you install Ninject by using the Nuget package Ninject.MVC3 then it will automatically configure all this for you, and you need only add your bindings to the RegisterServices() section of NinjectMVC3.cs
There's a lot more to it than this, but this should give you a basic understanding. Dependency Injection allows you to forget about the details of managing when objects are created and destroyed, you just specify in your constructor which dependencies you need, and assuming you have bindings for them in your configuration, MVC will take care of creating and destroying them for you. You just use them.
EDIT:
To be clear, I don't recommend you use the examples I give above. They are just simple illustrations of how DI works. In particular, the Get() syntax is known as "Service Location" and is considered to be bad. However, ultimately some code, somewhere must call Get(), it's just buried deep in the framework.
As Adam mentions, binding directly to the data entities context isn't a great idea, and you should eventually move to using an interface based approach.
I would never inject a concrete type here - you are directly coupling to a data access implementation.
Instead bind to IDbContext (or IUnitOfWork) - these are interfaces you define with a backing concrete implementation of DbContext, this way you can easily abstract away what technology you are using, making it more swappable, testable, maintainable, etc.
for ex:
http://blogs.planetcloud.co.uk/mygreatdiscovery/post/EF-Code-First-Common-Practices.aspx#disqus_thread
I am brand new to IoC and thus have been following the examples provided by Jeffery Palermo in his posts at http://jeffreypalermo.com/blog/the-onion-architecture-part-1/ and in his book hosted here https://github.com/jeffreypalermo/mvc2inaction/tree/master/manuscript/Chapter23
Most important to note is that I am not using a pre-rolled IoC container, mostly because I want to understand all the moving parts.
However, I am creating a windows service rather than an ASP.NET MVC webapp so I am little bogged down on the startup portion. Specifically, in the web.config he registers an IHttpModule implementation INSIDE the infrastructure project as the startup module and then uses a post-build event to copy the necessary dlls into the website directory to get around having a direct dependency in the web project itself.
I don't think I have this type of luxury in a true windows service, so how do I achieve something similar, should I have a small startup project which has dependencies to both the Infrastructure and Core, or is there another method to get around the compile-time restrictions of the windows service?
Thanks in advance.
Based on the tags of this question (c#) I'm assuming that you'll implement the Windows Service by deriving from ServiceBase. If so, the OnStart method will be your Composition Root - this is where you compose the application's object graph. After you've composed the object graph, composition is over and the composed object graph takes over.
In OnStop you can decommission the object graph again.
There's nothing stopping you from implementing the various components of the resolved object graph in separate assemblies. That's what I would do.
I think you missunderstood the role of an IoC framework.
To answer your question
but doesn't the reference imply dependency?
Yes it does, but on an other level. IoC is about dependencies between classes.
Instead of using new Something() in your class you provide a constructor which requires all dependent interfaces. This way the class has no control which implementation is passed to it. This is inversion of control. The IoC Container is just an aid to help managing the dependencies in a nice manner.
Say you have a ICustomerNotificationService interface with an implementation like
public class MailNotificationService : INotificationService
{
IMailerService _mailer;
ICustomerRepository _customerRepo;
IOrderRepository _orderRepo;
public MailNotificationService(IMailerService mailer,
ICustomerRepository customerRepo,
IOrderRepository oderRepo)
{
// set fields...
}
public void Notify(int customerId, int productId)
{
// load customer and order, format mail and send.
}
}
So if your application requests an instance of ICustomerNotificationServcie the container figures out which concrete implementations to take and tries to satisfy all dependencies the requested class has.
The advantage is that you can easily configure all dependencies in your bootstrapping logic and be able to change the behaviour of your application very easily.
For example when testing you start the application with an IMailerService implementation which writes the mails to a file and in production mode a real mail service is wired. This would not be possible if you newed up say a MailerService in your constructor instead of taking it as a parameter.
A good IoC container can handle much more, for you like lifetime management, singletons, scanning assemblies for Types you want to register and many more. We based our entire plugin system on Structure Map for example.
You may want to take a look at this blog article and its second part.
So I have a piece of software containing a brunch of service classes. Those services take some dependencies though their respective constructors.
I have designed with dependency injection in mind, but developers who are going to build on top of the software, may not want to use DI. Therefore I have not implemented an IOC container, so it is up to the developer to introduce one if desired.
My problem is that the software comes with an administration website, which uses these services.
I don't want to hardcode the service dependencies in the site, because I want to make it possible for the developers to switch them if they want to.
So how should I go about this?
I was thinking about introducing a factory for services, and give it a fixed static location somewhere. Then use it on the site.
public class ServiceFactory : IServiceFactory
{
public static IServiceFactory Current { get; set; }
static ServiceFactory()
{
Current = new ServiceFactory();
}
public TService Create<TService>()
{
// Creation logic here.
}
}
Developers will be able to control things by setting their own implementation of IServiceFactory to the static ServiceFactory.Current property.
Is this the way to go?
Two things I would like to note.
What you are proposing is not Dependency Injection, rather Service Location. They are not the same.
Ideally dependency injection is fully transparent to a developer. I.e. the true dependencies enter through the constructor and not via an indirection.
Have you looked into the CommonServiceLocator library? It is designed to provide an abstraction layer over an IOC container, however you could equally use it to abstract a service factory as you describe, that way your application would be able to resolve its dependencies without necessarily knowing whether they were coming from DI or a factory implementation...