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.
Related
I have a solution with multiple projects - similar to below:
WebAPI
ICustomerService.cs
Business Logic
CustomerService.cs
IDatabaseService.cs
Database Access
DatabaseService.cs
Previously the WebAPI project had a reference to the business logic, then that had a reference to database access. I am trying to invert this logic.
Currently, I am using Unity in my WebAPI project to resolve the interfaces with implementations from the business logic layer, however once I have inverted my logic so that the business logic layer has a reference to the WebAPI layer the Unity registration doesn't work without a circular reference:
var container = new UnityContainer();
container.RegisterType<ICustomerService, CustomerService>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
When I am trying to register my types, the ICustomerService lives in the top project, CustomerService is invisible to it.
I have read about having a separate project to house the unity configuration but that would create a circular reference also. How can I make this work?
Why do you wanna invert that? Seems to me like the only way of doing it. The WebAPI project is the main entrance (if it was self-hosted, it would contain a programs.cs). This project would also contain your composition root for setting up dependency injection and resolving types (this is handled by the WebAPI). See also Composition Root. Could you explain to me the benefit of doing this?
Also be aware that it is bad practice to spread out the IoC container cross projects. Only the composition root (main) should know about the fact that Unity is being used. Also avoid using the ServiceLocator pattern.
The objects in the different projects should just have a reference/dependency through for example the constructor.
If you think about it like that the Controller is dependent on ICustomService, CustomerService is dependent on IDatabaseService.
Also a note: I would put the implementation and interface in the same projects.
WebAPI
Controller
Business Logic
ICustomerService.cs
CustomerService.cs
Database Access
IDatabaseService.cs
DatabaseService.cs
You are on the right path. Your controller should inject the icustomerservice implementation in the constructor and the service should inject the idatabaseservice in its constructor.
public FooController(ICustomerService svc)
...
public CustomerService(IDatabaseService db)
...
And add the database DI config
container.RegisterType<IDatabaseService, DatabaseService>();
container.RegisterType<ICustomerService, CustomerService>();
When you are ready to use the new implementation, just change the reference in the config to instantiate the new implementation.
The interfaces should be in a project together and the implementation should be in a project together. The new and old implementation should share a common interface.
I am sorry if the question is trivial and already anwsered. I have been looking for an anwser, but all I was able to find were images and UMLs of the given situation without explaination. I have started reading the .NET Domain-Driven-Design book and I find myself hitting a brick wall in the start. My problem is that the author suggest creating a base class for Entities, this base class is placed in the Infrasturcture layer. This class will be inherited by all Entity classes in the Domain. That seems very uncommon and counter intuitive , at least to me. So I am trying to follow the book, but I can't understand why is this presented as a good idea, because I have a fear of circular dependency in the future development of the project, and can't understand why should the Entity Base class be outside of the Domain. Thank you.
EDIT:
I am afraid of cyclic dependency because in the chapter that preceeds the implementation phase the Author describes a downflow of dependancy. Starting from UI ->Application layer -> Domain while Infrastructure layer is not referencing anyone, but everyone references the Infrastructure layer. So I am having trouble understanding why should the Domain refrence the Infastructure? Regarding DDD (I assume) the Domain should be independant of other layers. So I just wanted to ask is the Domain -> Infrasturcture dependancy a common thing, or should there be a better/cleaner solution ?
The book I'm reading is called .NET Domain Driven Design in C# Problem-Design-Solution
EDIT On base of architecture depiction:
This link provides an image that depicts the architecture of the design at hand. The same image is provided in the book that I am following.
https://ajlopez.wordpress.com/2008/09/12/layered-architecture-in-domain-driven-design/. Thank you for your feedback and your answers.
Putting the base class for entities in the infrastructure layer is only a good idea if you have a layered architecture that puts infrastructure at the bottom - which is not what most architectures do nowadays.
So I'd recommend against this. Put the entity base type in the domain layer.
Nobody is going to ask "what domain concept is this?" if you name it appropriately. Make sure the class is abstract and properly documented. This will further clarify the situation.
With DDD, architectures that put the domain in the "center" (e.g. Hexagonal Architecture) are usually a better fit than classical layered architectures with infrastructure at the bottom. The important property of such architectures is that all dependencies point inwards, i.e. towards the domain.
It's called a layer supertype and is a common pattern.
In general, it's convenient to "hide" all infrastructure code that is required for your domain entities (such as database IDs needed by the persistence layer but not by the domain) in a common base class, such that the actual domain classes are not polluted by infrastructure code.
I agree that you should avoid circular dependencies. However, you don't need to actually move the base class to a separate project (to avoid circular dependencies). I guess what the authors mean is that semantically this base class belongs to the infrastructure layer since it contains database IDs.
If you follow principles of onion architecture, then the domain is the middle layer (no dependencies) and infrastructure is the outer layer (has dependencies).
You don't want your domain model to be dependent on infrastructural concerns, so this means your base class definitely belongs to the domain layer. The idea is that any change in infrastructure (or any technical change for that matter) does not impact the domain/business/application layers.
Also, try to program against interfaces, for which the concrete implementation is injected at run time. This also avoids any coupling to infrastructural concerns in the middle layers.
Domain Driven Development architecture is a layered design that can be really good when you need to separate business rules (user requirements) from the rest of the project.It puts the Domain in the center of the development.
It is quite usual to see concepts such as Dependency Injection and Inversion of Control when implementing a DDD architecture.
The example below is one of the many ways to put Domain in the center of the application, its just for you to have something in mind.
Domain : Contains interfaces and classes that are part of the business rule. (It does not implement anything, every method is passed through dependency injection from the infrastructure level).
Infrastructure: Implements all the interfaces created at domain level. This layer is responsible to design all "techological" behaviors of the application. This layer reference Domain.
Presentation: It is the User Interface. Connects Domain and Dependency Injection layers. This layer can see Dependency Injection and Domain.
Dependency Injection: Solve the dependency problem. It returns an interface implementation passed by parameter. This layer can see Infrastructure and Domain.
As example shown below: (I am using C#)
Domain Level:
As you can see, there are no actual implementation of the method. Only a dependency call finding an implementation for the interface IFight.
public class Samurai
{
public void Attack()
{
/*There are no class coupling here. 'Solve' receives an Interface as
parameter and do its job in order to return an object of the instance
and it calls the method Attack*/
Dependencies.Solver<IFight>().Attack(); //Forget about this right now. You will understand it as the post goes on.
}
}
Then we need to implement an interface to be implemented at infrastructure level.
public interface IFight
{
/*This interface is declared at the domain, altought, it is
implemented at infrastructure layer.*/
void Attack();
}
To make dependency injection works, it is need to implement it at domain level.
public class Dependencies
{
private static ISolve _solver;
public static ISolve Solver
{
get
{
if (_solver == null)
throw new SolverNotConfiguratedException();
return _solver;
}
set
{
_solver = value;
}
}
}
And also a Solver:
public interface ISolve
{
//This interface will be implemented at DependencyInjection layer.
T Solve<T>();
}
Infrastructure level:
Implementation of the interface
public class Fight : IFight
{
public void Attack()
{
Console.WriteLine("Attacking...");
}
}
Dependency Injection level:
Now it is important to set the injection
public class Solver : ISolve
{
private UnityContainer _container = new UnityContainer();
public Solver()
{
/* Using Unity "Framework to do Dependency Injection" it is possible do register a type.
When the method 'Solve' is called, the container looks for a implemented class that inherits
methods from a certain interface passed by parameter and returns an instantiated object.
*/
_container.RegisterType<IFight,Fight>();
}
//This is where the magic happens
public T Solve<T>()
{
return _container.Resolve<T>();
}
Explanation of the Dependency at Samurai Class:
//We are making a request of an interface implementation for Dependency
Solver. The Domain does not know who what class is doing it and how.
Dependencies.Solver<IFight>().Attack();
Presentation Level:
Samurai samurai = new Samurai()
samurai.Attack();
Conclusion:
We can see that domain is at the center of the implementation, and every business rule can be easily seen at that level whitout technical stuff being in the middle of it.
If I use the Repository Pattern in an ASP.NET MVC Application I need DI to let the program know, to interface the classes must be mapped. If I implement Unity I need to add the DAL project to my MVC project, and then register the types in the global.asax.
In my mind, I think it's bad to add the namespace of the DAL Layer to the MVC project, there is a business layer also in between. I think, it would be beautiful to inject the DAL classes in the business layer and only the business layer mappings in the MVC app.
What's the way to go here? Do you have suggestions?
UPDATE:
To make it clear to me. In the service layer, there are only DTO's and the DI for the business and data access layer. In the service layer I map the DTOs to the domain model. What I don't understand is, how can I call the business layer methods then?
If you want to be pragmatic, a true 3-tier architecture requires a service layer. Between the service and MVC are Data Transfer Objects (DTOs). The service layer hides both the DAL and the business layer.
If you set it up like this, the MVC itself knows nothing about DAL, only DTOs and Service (contracts).
Even if you don't use a distinct service layer, you can accomplish what you want, which is to decouple the MVC application from the DAL project using DI.
The way to do this is to add a couple of projects/assemblies in between that wires up your IoC container with specific instances of the interfaces you have defined.
I typically use this naming convention:
MyCompany.MyProject.Infrastructure
MyCompany.MyProject.Abstract
Your main MVC project would then have a reference to your Abstract and Infrastructure projects. Your Infrastructure project would have a reference to the Abstract and instance specific projects like the Business and DAL projects. Within Infrastructure project you wire up the dependencies.
You'll have to setup a mechanism for your MVC project to bootstrap your IoC in the Infrastructure assembly. You can do that in your global.asax or as an App_Start method and call a Registration class within your Infrastructure assembly.
We use StructureMap, but the concept is the same. Here's some sample code.
In your MVC App, create a App_Start method to setup the DI.
public static class StructuremapMvc
{
public static void Start()
{
// Create new Structuremap Controller factory so Structure map can resolve the parameter dependencies.
ControllerBuilder.Current.SetControllerFactory(new StructuremapControllerFactory());
IContainer container = IoC.Initialize();
DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(container);
}
}
In your Infrastructure assembly, wire up the dependencies.
public static class IoC
{
public static IContainer Initialize()
{
ObjectFactory.Initialize(x =>
{
x.Scan(scan =>
{
scan.TheCallingAssembly();
scan.WithDefaultConventions();
});
x.For<IRepositoryNum1>().Use<Num1Repository>();
x.For<IRepositoryNum2>().Use<Num2Repository>();
x.For<IRepositoryNum3>().Use<Num3Repository>();
});
return ObjectFactory.Container;
}
}
You should use DI to inject the Domain/DAL interfaces into your constructors. This has a lot of upside including allowing you to moq your interfaces when you write your unit tests. You can use Autofac to handle the injection.
I am thinking about using of DI and Unity in my project. And I have a question: how it will reduce coupling? From my point of view, it is increasing of coupling, because:
I need to create UnityContainer and register all types there. It means that I need to have the reference to all assemblies in assembly where this container is created.
IUnityContainer UnityContainer;
//....
IUnityContainer UnityContainer= new UnityContainer();
UnityContainer.RegisterType<IMyService, CustomerService>();
I need to create an instance of my service using Resolve but it means that I need to have the reference to assembly with container.
var service = SomeClassWithContainer.UnityContainer.Resolve<IMyService>();
Have I misunderstood something or in reality it is increasing of coupling?
I think you misunderstood how your dependencies should be resolved.
1.) A reference to Unity should only be needed in your bootstrapping code which is at a single central spot in your application.
2.) Once bootstrapping is done all dependencies (ideally) are resolved using constructor injection which is automatically done by Unity if the containing class is resolved via Unity - it is trickling down the object graph. The example you use is really just the "service locator" pattern and not DI.
This does reduce coupling since instead of directly creating a concrete class your class depends on, you "inject" dependencies (again ideally some abstraction like an interface) into your class which allows you to substitute those dependencies with other classes i.e. in the unit testing scenario.
Your question contains an example of the Service Locator anti-pattern:
public class UsesMyService
{
private readonly IMyService _service;
public UsesMyService()
{
_service = SomeClassWithContainer.UnityContainer.Resolve<IMyService>();
}
}
This is fundamentally different than the Dependency Injection pattern because of the direction the information flows: in the above example, you reach out and ask for the service, whereas in the example below, you are handed the service:
public class UsesMyService
{
private readonly IMyService _service;
public UsesMyService(IMyService service)
{
_service = service;
}
}
This pattern, known as constructor injection, decouples the UsesMyService class from details about the surrounding infrastructure. Now, anyone with an implementation of IMyService can create instances of UsesMyService without having to know to configure a central static location.
How would they even know what to configure? They would either need the source code or some documentation telling them that the class depends on IMyService. The constructor parameter cleanly expresses that requirement to consumers without any external reference.
If you follow this pattern throughout your libraries, you bubble the responsibility of assembling the objects all the way to the outermost layer, known as the Composition Root. This single location, usually the top-level application class, is the only place with references to all of the libraries you are using. That is where the container lives, and no other class in your entire solution needs to reference it.
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.