So, this is the first time I'm dealing with DI, please correct me if I misunderstood the whole DI thingy.
These are few of my projects:
Web Application/ Web API Project - Depends on Service Class + inject Automapper (Configuration only applicable for current project)
Service (Class Library) - Depends on Data Class + inject Automapper (Configuration only applicable for current project)
Data (Class Library)
My intention was to have each project having its own DI container (says Unity DI). I'm not sure that each project can have its own DI container.
I have read some of the article, showing that it cannot be done (not sure if i interpret them correctly) but I'm not sure why?
If it cannot be done, can anyone explain it and how can I achieve this and I doesn't want to register the classes in Data Layer in the Application Layer DI.
If each project can have its own DI, when registering the IMapper as instance will it override IMapper of other layers?
My intention was to have each project having its own DI container (says Unity DI). I'm not sure that each project can have its own DI container.
As explained here, you should compose all object graphs:
As close as possible to the application's entry point.
This place is called the Composition Root:
A Composition Root is a (preferably) unique location in an application where modules are composed together.
In other words, the only place that you should use your DI container and configure your application's dependencies is in the start-up project. All other projects should be oblivious to the container and should purely apply Constructor Injection.
I have read some of the article, showing that it cannot be done
It can be done, but you shouldn't.
If each project can have its own DI, when registering the IMapper as instance will it override IMapper of other layers?
This problem goes away if you apply the Composition Root pattern. In the Composition Root you have full control over which component gets which dependency.
PRO TIP: Read this book.
Related
Have a project structure where I have a couple of layers
Api
Bll
Dal
Utility
When say a order request is received by the Api there is a couple of steps that we need to take.
Like:
Validate the input
Save the customer
Save the order
Validate payment
Save final order status
All of these require different classes from the Bll
And the classes inside the Bll requires classes from Dal and maybe other Bll or from Utility.
So now inside the Api I need to register the whole chain of what might be needed like
Register<IValidateService,ValidateService>()
Register<ICustomerService,CustomerService>()
Register<ICustomerDatabaseService,CustomerDatabaseService>()
Register<IUtilityService,UtilityService>();
Maybe all of the above just to get the CustomerService working, and then we need to do this for a lot more services and I will have to reference the Dal layer inside the Api layer.
And in the long run I feel that everything will become really bloated.
Would be good if I could just Register the CustomerService and then that will register it's dependencies by itself or something.
Maybe it is fine to have the entry level to be aware of everything?
Any ideas on how to solve this or am I overthinking things?
Thank you
My suggested solution for auto-registration is the following:
Use Autofac.
Create a public DependencyModule class derived from Autofac.Module in your Api, Bll, Dal and Utility projects.
Override the Load method and register only types that are in that project.
In your startup project (Api) use my nuget package to automatically discover and register all your DependencyModule classes into the DI container.
At the end you will have something like this:
Utility
DependencyModule.cs - registers all the utility types that need to be injected.
Dal
DependencyModule.cs - registers all the DAL types (e.g. DbContext) that need to be injected.
Bll
DependencyModule.cs - registers all the BLL types that need to be injected.
Api
DependencyModule.cs - registers all the API types (if any) that need to be injected. E.g. filters, etc.
In Program.cs or Startup.cs you register only my Autofac module that will discover and register all your modules above.
See my example solution's description and implementation.
This way each injectable type registration is done in its own assembly and dependent services do not need to worry about it.
Alternative solution - uses Microsoft DI
Instead of Autofac modules you can create extensions methods for IServiceCollection type in each of your project and register the types that are in that project.
Then in your Program.cs or Startup.cs just call each extensions method.
At the end you will have something like this:
Utility
IServiceCollectionExtensions.cs - registers all the utility types that need to be injected.
Dal
IServiceCollectionExtensions.cs - registers all the DAL types (e.g. DbContext) that need to be injected.
Bll
IServiceCollectionExtensions.cs - registers all the BLL types that need to be injected.
Api
IServiceCollectionExtensions.cs - registers all the API types (if any) that need to be injected. E.g. filters, etc.
In Program.cs or Startup.cs call each of the extensions methods.
Note
Actually you can combine MS DI with Autofac so that you can enjoy the advanced features of Autofac and use specific extension methods for IServiceCollection at the same time.
In that case you should know that the order of registrations is this:
MS DI registrations: ConfigureServices() method
Autofac registrations: ConfigureContainer<T>() method
All the MS DI registrations will be populated into the Autofac container.
Dependency injection should be done at the application layer, which means the application must specify (effectively, choose) all of the dependencies in order for it to work correctly. This does mean it will be "bloated" in the wiring/startup phase, and does mean the app layer will have to deal with dependencies it might not normally care about.
That said, there's nothing wrong with your library code providing sane base implementations and wiring of these to alleviate the app layer's burden of figuring out what to wire up.
That means you can do one of
add the statements for registration manually and explicitly in your startup (total control, and extremely obvious how things are setup)
create a convenience method that contains common wiring in your library (less control, but less code to deal with when wiring). This is common in ASP.NET (see the AddXxx() and UseXxx() patterns).
discover dependencies. This uses reflection (usually) to find the implementations of all the dependent interfaces, and auto-register them). This is usually from a third-party like AutoFac. It's not built in to .NET.
I've followed the msdn document on the onion architecture in .net core here, but it seems you can't really have the UI only know about the service layer, without duplicating code. On the last part of the article (The UI), the startup file is accessing the repo. Is this logical? If so why?
On the last part of the article (The UI), the startup file is
accessing the repo. Is this logical? If so why?
I believe you are referring the following code -
services.AddDbContext<ApplicationContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
services.AddTransient<IUserService, UserService>();
services.AddTransient<IUserProfileService, UserProfileService>();
It is normal for UI Project to reference other projects, and register dependencies in IoC container, because Composition Root should be placed as close to the application's entry point as possible.
var userService = new UserService();
If you instantiate UserService using new keyword in UI, they become tightly coupled - a change in one class forces a change in another.
IoC container solves the dependencies issue by resolving dependencies at runtime and pass them as needed.
If you want to know more about DI, you might want to read Dependency Injection in .NET by Mark Seemann and Adaptive Code via C# by Gary McLean Hall
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'm trying to understand what CompositionRoot is about.
Right up to now I never found a deep description of what it is about,
only short statements of what shall not be done.
Is the Bootstrapper that comes along when leveraging caliburn.micro already that what is meant "CompositionRoot"?
Or is it closer to the servicelocator antipattern, as it can deliver merely anything that is inside the assembly and it's dependencies.
If someone has a good description of CompositionRoot, please share.
I already know the ploeh blog.
If I see that CompositionRoot leads to better architecture and / or helps me solve problems, I'm still willing to buy the book. But right know there is not enough
information around for me to see what it will help.
update
Let's pretend that all of my ViewModels get an EventAggregator injected (constructor injection). Now I want to dynamically create those ViewModels when they are needed.
I can register types beforehand (in the CompositionRoot), but how would I resolve dependencies later? As far as I understand, the Container should not be touched after the composition root. Definitly I do not want to create all instances before I need them (that would make the application start slow). Is "Register - Resolve - Release" meant here?
(that pattern is coined in the ploeh blog, too)
I assume you've seen Mark's article at http://blog.ploeh.dk/2011/07/28/CompositionRoot.
As it states:
A Composition Root is a (preferably) unique location in an application where modules are composed together.
And that this should be:
As close as possible to the application's entry point.
In the case of Caliburn.Micro, the Bootstrapper class provides a ConfigureContainer method for you to override and compose you modules.
Ideally, it will only be your composition root that has a reference to your IoC container.
Caliburn.Micro will resolve your shell view model (if you use the generic version of the Bootstrapper) via your container.
It does also supply a static IoC class which is an implementation of the Service Locator (anti) pattern if you do need to reference the container outside of your composition root.
Update
If you wish to resolve types via your container at runtime after your composition root (for example if you have complex dependency chains) then use factory types.
These factory types would also have a reference to your IoC container. You could either:
Pass a reference to your container as a dependency to the factory type
Use the Service Locator pattern in your factories (e.g. the Caliburn.Micro IoC class)
Some IoC containers such as Castle Windsor and (using an extension) Ninject will generate factory types for you based on a factory interface and conventions (this is the nicest option)
Say I have the following 4 .net assemblies:
Winforms UI
Business Logic
SQL Server Data Access (implementing an IRepository)
Common Interfaces (definition of IRepository etc.)
My business logic (2) makes calls to the data access layer (3) through IRepository (defined in 4) using constructor dependency injection. However when I ceate a business object I need to pass in an actual repository. I do this by having a singleton class in my business logic layer return the currently in use concrete object implementing IRepository. I am coming to the conclusion that this is a bad thing, as my business logic layer now has to reference 3 as well as 4.
I think I need a IoC Container but the question is where I create/put it as it seems that wherever I create this (1 - UI)? will also need to hold a reference to 3 (SQL Server Data Access). Am I not just moving the problem rather than achieving actual decoupling?
Do I create the IoC Container in the UI. Or expose it through another new assembly.
(I'm using C#, .net 3.5 and AutoFac)
Thanks.
IoC container generally should be created in the host project (application entry point). For the Windows.Forms application that's the exe project.
Generally in simple solutions (under 10 projects), only a host project should have a reference to IoC library.
PS: Structuring .NET Applications with Autofac IoC
When registering components there are several possibilities:
Registration in code:
directly
Problem: you have to reference everything ( you are here)
indirectly
Problem : to find out what has to be registered
Solution:
use attributes
use marker interface as IService
use conventions (see StructureMap)
Registration with configuration file:
let the container do everything
read the file yourself
Top level is a way to go (UI, as Rinat said).
Now as for references, simplest way is just to go over all assemblies in the current folder and use some convention to get the services out. Attributes work fine, putting registrar classes in each assembly works fine, whatever suits you. The code for extracting everything should probably be in a separate assembly, unless your IoC framework already does that.
The module distinction and the "scopes" defined by the modules exist mostly at compile-time. In the run-time it's all one big mess ;) This is used by most IOC containers and they don't really care about where they are located. The IoC container for a web-app will typically be created at the outermost level (very close to the web-container itself).
It's true that you could create it anywhere, but I'd introduce an extra layer, let's call it 3.5.
Your current 3 would be where your IoC resides for Data Access - this would become a wrapper for your actual DAL. Based on your config, 3 would create either a mock repository or a concrete one.
So 2 still references 3, but it's just an interface to the actual DAL which is configured through your IoC framework.
Alternatively, you could roll your own 'el-cheapo' IoC - change your Big Ugly Singleton to a Static Gateway - Abstracting IoC Container Behind a Singleton - Doing it wrong?