Dependency injection modular dependency registration - dependency-injection

I try to design my applications always in a modular fashion. I want to be able at any given to swap modules.
Using the dependency injection pattern allows me to do just that. But there is something that keeps bothering me a lot.
In most of the code I come across there is a single place where interfaces are linked to the desired interface. For example in asp.net vnext it looks something like this:
public void ConfigureServices(IServiceCollection services)
{
// business-layer
services.AddTransient<IArticleRepository, ArticleRepository>();
// data-layer
services.AddTransient<IDataConnection, DataConnection>();
}
But I don't like that there is only one place to do the registration. I would rather have each module register their own interfaces/implementations:
In my business layer (module)
public void ConfigureServices(IServiceCollection services)
{
// business-layer
services.AddTransient<IArticleRepository, ArticleRepository>();
}
In my data layer (module)
public void ConfigureServices(IServiceCollection services)
{
// data-layer
services.AddTransient<IDataConnection, DataConnection>();
}
Is there any pattern, or best-practice to do this kind of things? I could create some interface and on load go through all the implementations of this interface, but I'm not sure if this is the best way to do this.

Is there any pattern, or best-practice to do this kind of things?
Yes and no. There's the Facade pattern where you provide a simplified API to clients that don't need fine-grained control of your API. The Facade pattern doesn't explicitly concern itself with Dependency Injection, but you can always provide a default composition of services if that's a meaningful thing to do. There are more details in my article DI Friendly Library.
That said, it's important to keep the API open, so that the Facade is only one of the options you provide to clients. If you pre-compose an object graph within a library, and don't provide clients any way to circumvent that default composition, such a library would be a monolithic black box. All external benefits from Dependency Injection would be gone, because a client wouldn't be able to replace or extend services.
Do follow the guidelines outlined in the DI Friendly Library article, but be sure to avoid the Conforming Container anti-pattern.

i would say that way/place of configuring your DI depends highly on your DI framework. some frameworks let you do per-module configuration others require one global configuration. in the latter case you can manually delegate to your submodules (just pass the IServiceCollection to submodule configuration code).
regarding best practices: i rarely see usage of DI to have multiple production implementations. usually there is just one production implementation and DI is used just to wire together everything without the boilerplate. but many different implementations (usually mocks) are used in testing usually with manual wiring without the DI framework. if that's also your case then your gut-felling is right: it would be nice to have DI framework that scan the whole code, take the default/only implementation and inject it as a dependency. if your DI framework provides that functionality you're lucky. if not, you have to implement it by yourself

Related

Dependency injection - trying to avoid using a service locator

Following the guidelines I read in:
https://www.devtrends.co.uk/blog/how-not-to-do-dependency-injection-the-static-or-singleton-container
I want to try and avoid using a service locator.
But on the other hand, I don't register all the types in the startup.cs file. I don't think this is right that all these internal types are referenced in the main startup.cs
I currently have a factory class that has a collection of builder classes.
Each builder class is in charge of creating a specific object.
I don't want to create all these builder classes in advance as I might not need to use them and creating them is a bit heavy.
I saw an example of how to achieve this in the link above. However the startup.cs class needs to know all these builders. I don't think this is appropriate, I'd rather have the factory class be the only one that is exposed to them. I was trying to understand if there is some kind of func/action method that I can inject from the startup.cs file into my factory class. This func/action will be in charge of creating/registering the builders and then I can activate this func/action within the class factory. I'd like this func/action to receive the interface/class/maybe name of the builder but using generics isn't working. I searched a lot and didn't find any solution so I assume this is not possible.
Seems I have 2 options:
1. Use service locator. This way only the factory class will know the builders. However if in the future, if I want to change the DI I need to "touch" the factory class (I'm contaminating the factory class). Wanted all the DI code to be located only in the startup.cs class.
2. Register the builders in the startup.cs but now the startup.cs is aware of the builders. This kinda couples the code, not really single role of responsibility
It would have been great to inject the factory class a func/action from the startup.cs that would do the registration but the factory class itself activates it.
Is this possible?
I want to try and avoid using a service locator
Great, because the Service Locator is an anti-patttern.
don't register all the types in the startup.cs file.
You should do your registrations in one single 'area' of your application: the start-up path. This area is commonly referred to as the Composition Root (the place where object graphs are composed).
I don't think this is right that all these internal types are referenced in the main startup.cs
No matter how you design it, the startup assembly is the most volatile part of the system and it always depends on all other assemblies in the application. Either directly or transitively (through another referenced assembly). The whole idea of Dependency Injection is to minimize the coupling between components and the way to do this is to centralize coupling by moving it to the Composition Root. By making types internal however, you are decentralizing object composition and that limits your flexability. For instance, it becomes harder to apply decorators or interceptors for those registered types and control them globally. Read this question and its two top voted answers for more information.
I don't register all the types
The concern of having a Composition Root that is too big is not a valid one. One could easily split out the Composition Root into multiple smaller functions or classes that all reside in the startup assembly. On top of that, if you read this, you'll understand that registering all types explicitly (a.k.a. "Explicit Register") is typically pointless. In that case you're probably better off in using DI without a Container (a.k.a. Pure DI). Composition Roots where all types are registered explicitly are not very maintainable. One of the areas a DI Container becomes powerful is through its batch-registration facilities. They use reflection to load and register a complete set of types in a few lines of code. The addition of new types won't cause your Composition Root to change giving you the highest amount of maintainability.
I don't want to create all these builder classes in advance as I might not need to use them and creating them is a bit heavy
Creation of instances should never be heavy. Your injection constructors should be simple and composing object graphs should be reliable. This makes building even the biggest object graphs extremely fast. Factories should be reduced to an absolute minimum.
TLDR;
Register or compose your object graphs solely in the Composition Root.
Refrain from using the Service Locator anti-pattern; Whole applications can (and should) be built purely with Constructor Injection.
Make injection constructors simple and prevent them from doing anything else than storing their incoming dependencies.
Refrain from using factories to compose services, they are not needed in most cases.

Using MEF , what would be the Extensible points in a web application?

So, I've decided to use the Microsoft Extensibility Framework(MEF) with my new ASP.NET MVC web project. The project is a very typical employee management system, with 3 traditional layers :- a presentation layer (with views and controllers), a business layer (with business objects) and ofcourse, a data access layer. After some research, I read a lot, that MEF is supposed to help us implement the plug-in architecture.And this is where, I seem to get stuck. I'm not able to relate with this pluggable part. I'm pretty sure that, since MEF is the part of the core .NET framework, it is not limited to any specific kind of application, and is supposed to be useful in general. I just need to see my application structure in a new light, and that's where I need some helpful insights.
As I'm still trying to get started with MEF, my main question is; what would be the main extensible(pluggable) points in my application? What objects should one be typically composing using the MEF's compose method, and what would be the advantages of doing so using MEF instead of the traditional way?
MEF will not help you solve extensibility issues in the case you have described in the question, because it doesn't seem to have any. What MEF can bring to the table for this particular case is Dependency Injection. If you develop your application in a way that the presentation layer depends on business abstraction and the business layer depends on a data access abstraction rather than on concrete implementation, you will get a highly decoupled application that is easy to test, maintain and change without affecting unnecessary components. Here is one way to do this:
Lets say you have data access class that performs CRUD operations on employees:
[Export(typeof(IEmployeeRepository))]
public class EmployeeRepository : IEmployeeRepository
{
//Some logic here
}
As you can see the EmployeeRepository class implements IEmployeeRepository interface which adds the level of abstraction that is needed to develop a decoupled application. Now lets say that in the business layer you have a class that needs to call some method from the EmployeeRepository class. To be able to call a method of EmployeeRepository, you would need an instance of it. Without using MEF (or any other IoC framework, this would be a way to do it:
public class EmployeeManager
{
private EmployeeRepository _employeeRepository;
public EmployeeManager
{
_employeeRepository = new EmployeeRepository();
}
}
By using the above code sample, a hard dependency between the EmployeeManager and EmployeeRepository classes is created. This hard dependency is difficult to isolate when writing unit tests and causes any change of the EmployeeRepository class to directly affect the EmployeeManager class. By refactoring the code sample a little bit and putting MEF into the game, you'll get this:
[Export(typeof(IEmployeeManager))]
public class EmployeeManager : IEmployeeManager
{
private IEmployeeRepository _employeeRepository;
[ImportingConstructor]
public EmployeeManager(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
}
As you can see the EmployeeManager class now doesn't depend on the EmployeeRepository class, but it depends on IEmployeeRepository interface, in other words it depends on abstraction. And it doesn't create the instance of EmployeeRepository class by itself. That job is left to MEF. By now it should be clear that export and ImportingConstructor attributes are part of MEF and are used by it to discover parts and resolve dependencies at runtime. With the last code sample the classes are decoupled, easy to test and maintain and you can change the internal logic in EmployeeRepository class without making EmployeeManager class aware of it. Of course the contract between them, IEmployeeRepository have to be maintained.
The above said, can be used to decouple the presentation layer from the business layer also. Also the above said, can be implemented by using any other IoC framework, like Ninject, Autofac, StructureMap etc. The difference between these IoC frameworks and MEF is that if you use them, you'll need to configure at application start which instance gets created when some interface is encountered:
//something like this, in the case of Ninject
this.Bind<IEmployeeRepository>().To<EmployeeRepository>();
On the other hand, MEF has the ability to discover parts at runtime. On application start, you'll just need to inform it where to look for parts: Directory, Assembly, Type etc. The auto-wire capabilities of MEF (the ability to discover parts at runtime), make it more than a regular IoC framework. This ability makes MEF great for developing pluggable and extensible applications because you'll be able to add plugins while the application is running. MEF is able load them and let the application to use them.

Dependency Injection - Passing dependencies all the way down

I have an MVC application with a typical architecture...
ASP.NET MVC Controller -> Person Service -> Person Repository -> Entity Framework DB Context
I am using Castle Windsor and I can see the benefit of using this along with a ControllerFactory to create controller with the right dependencies. Using this approach the Controller gets a Service injected, which in turn knows how to construct the right Repository, which in turn knows the correct DbContext to use.
The windsor config is something like this...
dicontainer = new WindsorContainer();
dicontainer.Register(Component.For<IPersonService>().ImplementedBy<PersonService>());
dicontainer.Register(
Component.For<IPersonRepository>().UsingFactoryMethod(
() => new PersonRepository(new HrContext("connectionString"))));
It this the right way to do it? I don't like the UsingFactoryMethod, but can't think of another way.
Also, what if the Repository needed a dependency (say ILogger) that was not needed by the service layer? Does this mean I have to pass the ILogger into the service layer and not use it. This seems like a poor design. I'd appreciate some pointers here. I have read loads of articles, but not found a concrete example to verify whether I am doing this right. Thanks.
I try to avoid using factory methods (as you mentioned you felt this smelled funny). To avoid this, you could create a database session object that creates a new DbContext. Then your repositories just need to get an instance of IDbSession and use its dbContext property. Then, you can also easily control the scope of the IDbSession object (don't use singleton because it's not thread safe).
I wanted to make that point so that I could make this more important point... Make your constructors take in only objects that are registered in the DI container (no options or configurations in constructors). Options and configurations should be read/writen in classes whose sole purposes it is to read/write those values. If all classes follow this model, then your DI registration becomes easy and classes can just add whatever dependencies they need in their constructors.
If you are trying to use a third party library that has options in constructors, wrap that class in your own class that has an easy to consume constructor and uses a configuration class to read the values needed to pass to the third party library. This design also introduces a layer of abstraction between your code and the third party library which can then be used to more easily swap (or stub) third party libraries when necessary.

Service layer interdependency

I am designing an asp.net mvc application which uses a service layer. What if we have a service which depends on another service? For, instance, suppose we have the following model:
class UserService : IUserService
{
//implementation requires IEmailService
}
Sure, the concrete implementation EmailService can be injected into the constructor of UserService, but in my understanding, a service layer should mediate between UI and Domain Model, it's like a facade. I would define another layer in such a way that UserService depend on IUserModule and IEmailModule, in this way we could break the dependency between services, services being dependent on a lower layer (in my case module layer). Is it a correct approach?
Inside a common DDD architecture you'll find two kind of services Domain services (whose coordinate business operations among entities) and Application services (whose depend on the Domain services, and contain tasks related to the application and not to the business logic e.g. export to pdf is an application task. apply a discount is a business logic task).
So if you only have a kind of service, which I suppose covers both responsibilities. is totally valid to have interdependencies.
Sure, the concrete implementation EmailService can be injected into the constructor of
UserService, but in my understanding, a service layer should mediate between UI and Domain
Model
Well, it's a contract between to sides, not necessarily UI and Domain Model, but commonly.
it's like a facade.
Yes, a good service features a nice facade also accounting for performance.
this way we could break the dependency between services, services being dependent on a
lower layer (in my case module layer). Is it a correct approach?
What does module mean to you? Is IEmailService a service or a module to you? It seems correct to create the Facade in your case for your service. But you provide to few information about your system and your intent and your architectural challenges/priorities.
Dependency injection is something you should avoid as it increases coupling and complexity for an illusion of flexibility. MVC is also something to reconsider before you start your development because it is not good for anything more than simple applications that do CRUD operations. Web Forms is a more proven platform and is better for more usable applications.

StrcutureMap Wiring - Sanity Check Please

Im new to IOC and StructureMap and have an n-level application and am looking at how to setup the wirings (ForRequestedType ...) and just want to check with people with more experience that this is the best way of doing it!
I dont want my UI application object to reference my persistence layer directly so am not able to wire everything up in this UI project.
I now have it working by defining a Registry class in each project which wires up the types in the project as needed. The layer above registers its types and also calls the assembly below and looks for registries so that all types are registered throught the hierrachy.
E.g. I have UI, Service, Domain, and Persistence libraries. In my service layer the registry looks like
Scan(x =>
{
x.Assembly("MyPersistenceProject");
x.LookForRegistries();
});
ForRequestedType<IService>().TheDefault.Is.OfConcreteType<MyService>();
Is this a recommended way of doing this in a setup such as this? Are there better ways and what are the advantages / disadvantages of these approaches in this case?
This sounds good.
If you use default conventions, like having a default implementation OrderSevice for the interface IOrderService you can reduce the wiring by using conventions in StructureMap. The WithDefaultConventions is a method in the Registry to use default conventions. You can also specify your own convention and register it in the registry using the method With, see the StructureMap documentation

Resources