How can I manage multiples modules using IOC Containers - dependency-injection

I'm trying to create an application using multiples modules. I had an application with a single module but we just decide to split up.
We created two containers, the first one is moduleAContainer and the second one for moduleBContainer, I mean IOC contailers (Castle).
We have too an IoCWorker class that is responsible for keep an specific container static and provide some methods to resolve.
My problem is that, using ControllerFactory of Asp.net MVC for example, how can I decide with one should resolve my dependency?
Should be something like, IocWorker.Resolve("containername") but per web request? What is my parameter to decide it?
Can I do it using child containers?
Thank you so much.

Let me try to come up with a solution on your situation of two modules(Module A and B, by the way they both run same service interface ISaleAppService) having same interface (IUnitOfWork) with different implementation details solid classes.
So let's say it's a delivery app.
Module A uses Motorcycle to deliver
DeliveryServiceA : IUnitOfWork { // deliver asap using motorcycle }
Module B uses Truck to deliver
DeliverServiceB : IUnitOfWork { // deliver as loaded as possible using truck }
and the consumer, let's say ISaleAppService, buys the service and now, let's say it is not a concern of the consumer which service being used, Service(Module) A or B..
If that is the case, you need another service with implementation detail to make that decision for the user, mediator.. IMediator.
Consumer request => IMediator determines which service to use => choose between Service A or B (Module A or B).
If consumer needs to choose which service (which module), then probably you can provide key to distinguish such as input argument arg1.
Consumer request with key(arg1 or enum) via IUnitOfWork => IUnitOfWork determines which implementation block to choose (Module A or Module B) to send request, based on the key (or enum).
Whichever you design, I think there needs to be intermediate step no matter how you abstract using IUnitOfWork because there is implementation done differently behind the scene.

Related

How do I make Simple Injector prefer implementations of the "most derived" interface?

In my data access layer I have a repository hierarchy that looks like this:
<TEntity>
IEntityRepository<---------+ICustomerRepository
^ ^
| |
| |
| |
+ |
<TEntity> +
EntityRepository<----------+CustomerRepository
The IEntityRepository<TEntity> interface defines basic CRUD operations that will be useful regardless of entity type. EntityRepository<TEntity> is a concrete implementation of these operations.
In addition, there are repository types for operations that are specific to a particular entity. In the example above, I have a Customer entity, and the ICustomerRepository interface defines operations such as GetByPhoneNumber. The ICustomerRepository also derives from IEntityRepository<Customer>, so that the common CRUD operations will also be available for an instance of ICustomerRepository. Finally, CustomerRepository is the concrete implementation for the ICustomerRepository operations, and it also inherits from EntityRepository<Customer> for the common operations implementation.
So, going over to my actual question: I use Simple Injector to inject instances into my application. I register each of the specialized repository types in my container: CustomerRepository as the implementation of ICustomerRepository and so on.
To ensure new entity types can be added to the system and used without needing to create a new, concrete repository implementation as well, I would like to be able to serve the base EntityRepository<> implementation when an IEntityRepository<> of the new entity is requested. I've understood I can use the RegisterOpenGeneric method for this.
What I can't figure out is, when a generic repository is requested, how can I serve the specialized repository for that type if it exists, and the generic repository only as a fallback?
For example, let's say I do this in my application:
container.Register<ICustomerRepository, CustomerRepository>();
container.RegisterOpenGeneric(typeof(IEntityRepository<>), typeof(EntityRepository<>));
Most of the classes relying on repositories would request the ICustomerRepositorydirectly. However, there could be a class in my application requesting the base interface, like this:
public ContractValidator(IEntityRepository<Customer> customerRepository,
IEntityRepository<Contract> contractRepository)
{
...
What happens in the example above is:
customerRepository gets an instance of EntityRepository<Customer>
contractRepository gets an instance of EntityRepository<Contract>
What I want to happen is:
customerRepository gets an instance of CustomerRepository
contractRepository gets an instance of EntityRepository<Contract>
Is there any way to inform Simple Injector's resolution that if a derivation of a particular interface exists, this should be served instead? So for IDerived : IBase, requests for IBase should return an implementation of IDerived if it exists. And I don't want this resolution across the board, just for these repositories. Can it be done in a reasonable way, or would I need to manually iterate through all the registrations in the RegisterOpenGeneric predicate and check manually?
Assuming your classes look like this
public class CustomerRepository :
ICustomerRepository,
IEntityRepository<Customer> { }
You can register all the generic implementations of IEntityRepository<> using RegisterManyForOpenGeneric and the fallback registration stays the same.
UPDATE: Updated with v3 syntax
// Simple Injector v3.x
container.Register<ICustomerRepository, CustomerRepository>();
container.Register(
typeof(IEntityRepository<>),
new[] { typeof(IEntityRepository<>).Assembly });
container.RegisterConditional(
typeof(IEntityRepository<>),
typeof(EntityRepository<>),
c => !c.Handled);
// Simple Injector v2.x
container.Register<ICustomerRepository, CustomerRepository>();
container.RegisterManyForOpenGeneric(
typeof(IEntityRepository<>),
new[] { typeof(IEntityRepository<>).Assembly });
container.RegisterOpenGeneric(
typeof(IEntityRepository<>),
typeof(EntityRepository<>));
But you should note that if you use any lifestyle then these separate registrations may not resolve as you would expect. This is known as a torn lifestyle.
You can't use RegisterOpenGeneric or RegisterManyForOpenGeneric for this. You will have to hand-write some code to reflect over the type system and find the implementations to register by their specific interface.
In my opinion however you should not have custom repository. These one-to-obe mappings are cause you these grief and besides, you are violating the SOLID principles by doing so. If you can, consider a design as described here.

How to create two configured instances of the same service?

I have a service that interacts with a brokerage account's API. It works fine, but now I need to interact with two different accounts at the same brokerage.
It seems like the best way to handle this is to make it possible to configure the service to specify the target account and then instantiate two different instances, one for each account.
I'm not sure if this is supported in Grails or how to go about it.
Two questions:
Is there a better way to do this?
If not, how can I instantiate and configure two different service instances?
ADDITIONAL INFORMATION:
Both answers are near misses. Let me try to clarify:
I didn't want to get into the details, but it may help to explain what I'm after. I'm using the Interactive Brokers trading API, and they don't let you talk directly to their servers the way other brokerages do. You have to talk over a socket to their IB Gateway, which is a piece of software they provide that essentially proxies their servers. So your app talks to IB Gateway, and IB Gateway talks to Interactive Brokers' servers on your app's behalf.
The catch is that IB Gateway has to be logged in to an account as part of its configuration. So, in order to trade two different accounts, you have no choice but to configure two different IB Gateways, since each can only access the account that it is configured for.
So my Grails code for placing trades must select the right IB Gateway to talk to. That means it needs to know the IP address and port of the IB Gateway that corresponds to each account. Other than this setting for IP address and port, there is no difference between the two Grails services that communicate with IB Gateway.
What I want is to reuse the same service class, each being instantiated as a singleton, simply having a different IP address and port on which to communicate.
So making two different services is undesirable, since the code is otherwise identical. (And if I add a third or fourth IB Gateway, this becomes fairly smelly code.)
And this setting should exist for the life of the application, so I don't think a change in scope is really the answer, either.
I really want two instances of the same service, simply having different configurations.
I hope that helps explain the situation. What do you suggest? Thank you!
If the same business logic is applicable for both accounts but taking into consideration that you cannot have a single service class talking to the API for both accounts, then yes you can have 2 service classes (which are nothing but 2 different spring beans) with the default singleton scope.
class Account1Service{
}
class Account2Service{
}
I would also try if I can use inheritance here in this case, if I have common logic that can be shared across. But keep in mind, if you are inheriting a service class from an abstract class then the abstract class has to be placed in src/groovy that is, outside /grails-app/ to defy Dependency Injection. In that case you might end up with (untested, but you can adhere to DRY concept)
// src/groovy
abstract class BrokerageService {
def populateAccountDetails(Long accountId)
def checkAccountStatus(Long accountId)
}
//grails-app/services
class Account1Service extends BrokerageService {
//Implement methods + add logic particular to Account1
//By default transacitonal
}
class Account2Service extends BrokerageService {
//Implement methods + add logic particular to Account2
//By default transacitonal
}
Also keep a note that the scope is singleton, you would take extra care (better avoid) maintaining global scoped properties in Service class. Try to make as stateless as possible. Unless otherwise the situation or the business logic demands to use service level scopes like session, flow or request, I would always stick to the default singleton scope.
To answer your second question, you do not need to instantiate any of the grails service class. The container injects appropriate service class (using Spring IoC) when an appropriate nomenclature is used. In the above example, the service classes will automatically be injected if you follow this naming convention in classes where you wan tto use the services:
//camelCase lower initial
def account1Service
def account2Service
UPDATE
This is in response to the additional information provided by OP.
Referring to the above scenario, there can be only one service class in the default singleton scope to handle things perfectly. The best part, since you are going out of your network and not really worried about own database transactions the service class can be set to non-transactional. But again it depends on the situations need. Here is how the service class would look like.
//grails-app/service
class BrokerageService{
//Service method to be called from controller or any endpoint
def callServiceMethod(Long accountId){
.......
doSomethingCommonToAllAccounts()
.........
def _ibConfig = [:] << lookupIBGatewayConfigForAccount(accountId)
........
//Configure an IB Gateway according to the credentials
//Call IB Gateway for Account using data got from _ibConfig map
//Call goes here
}
def doSomethingCommonToAllAccounts(){
........
........
}
def lookupIBGatewayConfigForAccount(accountId){
def configMap = [:]
//Here lookup the required IP, account credentials for the provided account
//If required lookup from database, if you think the list of accounts would grow
//For example, if account is JPMorgan, get credentials related to JPMorgan
//put everything in map
configMap << [ip: "xxx.xx.xx.xxx", port: 80, userName: "Dummy"] //etc
return configMap
}
}
The scope of the service class is singleton which means there will be only one instance of the class in the heap, which also means that any class level property (other than methods) will be stateful. In this case, you only deal with methods which will be stateless and would suffice the purpose. You would get what you need without spending heap or without creating new instances of BrokerageService every time a trading happens.
Each trade (with an account assciated) will eventually call the service, lookup the credentials from db (or config properties, or flat files, or properties files) and subsequently configure the IB Gateway and call/talk to the gateway.
Grails services are supposed to be singletons by default, not having any state associated to what it is doing and usually only one instance. Namely, you wouldn't have instance fields in them, normally.
But if you override the default scope, you can have them. For example, you can make your service to be session scoped, adding this static variable:
static scope = "session"
Then you'll have one instance for each user session.
For your particular case, you may want to take a look at the prototype scope, which will give you a new instance of the service each time you need it injected. You just will have to make sure to always use that instance after it is injected, if you want them to act on the same data.
Take a look at the docs about Scoped Services.

Unit of Work with Dependency Injection

I'm building a relatively simple webapp in ASP.NET MVC 4, using Entity Framework to talk to MS SQL Server. There's lots of scope to expand the application in future, so I'm aiming for a pattern that maximises reusability and adaptability in the code, to save work later on. The idea is:
Unit of Work pattern, to save problems with the database by only committing changes at the end of each set of actions.
Generic repository using BaseRepository<T> because the repositories will be mostly the same; the odd exception can extend and add its additional methods.
Dependency injection to bind those repositories to the IRepository<T> that the controllers will be using, so that I can switch data storage methods and such with minimal fuss (not just for best practice; there is a real chance of this happening). I'm using Ninject for this.
I haven't really attempted something like this from scratch before, so I've been reading up and I think I've got myself muddled somewhere. So far, I have an interface IRepository<T> which is implemented by BaseRepository<T>, which contains an instance of the DataContext which is passed into its constructor. This interface has methods for Add, Update, Delete, and various types of Get (single by ID, single by predicate, group by predicate, all). The only repository that doesn't fit this interface (so far) is the Users repository, which adds User Login(string username, string password) to allow login (the implementation of which handles all the salting, hashing, checking etc).
From what I've read, I now need a UnitOfWork class that contains instances of all the repositories. This unit of work will expose the repositories, as well as a SaveChanges() method. When I want to manipulate data, I instantiate a unit of work, access the repositories on it (which are instantiated as needed), and then save. If anything fails, nothing changes in the database because it won't reach the single save at the end. This is all fine. My problem is that all the examples I can find seem to do one of two things:
Some pass a data context into the unit of work, from which they retrieve the various repositories. This negates the point of DI by having my Entity-Framework-specific DbContext (or a class inherited from it) in my unit of work.
Some call a Get method to request a repository, which is the service locator pattern, which is at least unpopular, if not an antipattern, and either way I'd like to avoid it here.
Do I need to create an interface for my data source and inject that into the unit of work as well? I can't find any documentation on this that's clear and/or complete enough to explain.
EDIT
I think I've been overcomplicating it; I'm now folding my repository and unit of work into one - my repository is entirely generic so this just gives me a handful of generic methods (Add, Remove, Update, and a few kinds of Get) plus a SaveChanges method. This gives me a worker class interface; I can then have a factory class that provides instances of it (also interfaced). If I also have this worker implement IDisposable then I can use it in a scoped block. So now my controllers can do something like this:
using (var worker = DataAccess.BeginTransaction())
{
Product item = worker.Get<Product>(p => p.ID == prodName);
//stuff...
worker.SaveChanges();
}
If something goes wrong before the SaveChanges(), then all changes are discarded when it exits the scope block and the worker is disposed. I can use dependency injection to provide concrete implementations to the DataAccess field, which is passed into the base controller constructor. Business logic is all in the controller and works with IQueryable objects, so I can switch out the DataAccess provider object for anything I like as long as it implements the IRepository interface; there's nothing specific to Entity Framework anywhere.
So, any thoughts on this implementation? Is this on the right track?
I prefer to have UnitOfWork or a UnitOfWorkFactory injected into the repositories, that way I need not bother it everytime a new reposiory is added. Responsibility of UnitOfWork would be to just manage the transaction.
Here is an example of what I mean.

Simplest explanation of how a DI container works?

In simple terms and/or in high-level pseudo-code, how does a DI container work and how is it used?
At its core a DI Container creates objects based on mappings between interfaces and concrete types.
This will allow you to request an abstract type from the container:
IFoo f = container.Resolve<IFoo>();
This requires that you have previously configured the container to map from IFoo to a concrete class that implements IFoo (for example Foo).
This in itself would not be particularly impressive, but DI Containers do more:
They use Auto-Wiring which means that they can automatically figure out that if IFoo maps to Foo and IBar maps to Bar, but Foo has a dependency on IBar, it will create a Foo instance with a Bar when you request IFoo.
They manage the lifetime of components. You many want a new instance of Foo every time, but in other cases you might want the same instance. You may even want new instances of Foo every time, but the injected Bar should remain the same instance.
Once you start trying to manually manage composition and lifetimes you should start appreciating the services provided by a DI Container :)
Many DI Containers can do much more than the above, but those are the core services. Most containers offer options for configuring via either code or XML.
When it comes to proper usage of containers, Krzysztof Kozmic just published a good overview.
"It's nothing more than a fancy hash
table of objects."
While the above is a massive understatement that's the easy way of thinking about them. Given the collection, if you ask for the same instance of an class - the DI container will decide whether to give you a cached version or a new one, or so on.
Their usage makes it easier and cleaner when it comes to wiring up dependencies. Imagine you have the following pseudo classes.
class House(Kitchen, Bedroom)
// Use kitchen and bedroom.
end
class Kitchen()
// Code...
end
class Bedroom()
// Code...
end
Constructing a house is a pain without a DI container, you would need to create an instance of a bedroom, followed by an instance of a kitchen. If those objects had dependencies too, you would need to wire them up. In turn, you can spend many lines of code just wiring up objects. Only then could you create a valid house. Using a DI/IOC (Inversion of Control) container you say you want a house object, the DI container will recursively create each of its dependencies and return you a house.
Without DI/IOC Container:
house = new House(new Kitchen(), new Bedroom());
With DI/IOC Container:
house = // some method of getting the house
At the end of the day they make code easy to follow, easier to write and shift the responsibility of wiring objects together away from the problem at hand.
You configure a DI container so it knows about your interfaces and types - how each interface maps to a type.
When you call Resolve on it, it looks at the mapping and returns the mapped object you have requested.
Some DI containers use conventions over configuration, where for example, if you define an interface ISomething, it will look for a concrete Something type to instantiate and return.

Why not pass your IoC container around?

On this AutoFac "Best Practices" page (http://code.google.com/p/autofac/wiki/BestPractices), they say:
Don't Pass the Container Around
Giving components access to the container, or storing it in a public static property, or making functions like Resolve() available on a global 'IoC' class defeats the purpose of using dependency injection. Such designs have more in common with the Service Locator pattern.
If components have a dependency on the container, look at how they're using the container to retrieve services, and add those services to the component's (dependency injected) constructor arguments instead.
So what would be a better way to have one component "dynamically" instantiate another? Their second paragraph doesn't cover the case where the component that "may" need to be created will depend on the state of the system. Or when component A needs to create X number of component B.
To abstract away the instantiation of another component, you can use the Factory pattern:
public interface IComponentBFactory
{
IComponentB CreateComponentB();
}
public class ComponentA : IComponentA
{
private IComponentBFactory _componentBFactory;
public ComponentA(IComponentBFactory componentBFactory)
{
_componentBFactory = componentBFactory;
}
public void Foo()
{
var componentB = _componentBFactory.CreateComponentB();
...
}
}
Then the implementation can be registered with the IoC container.
A container is one way of assembling an object graph, but it certainly isn't the only way. It is an implementation detail. Keeping the objects free of this knowledge decouples them from infrastructure concerns. It also keeps them from having to know which version of a dependency to resolve.
Autofac actually has some special functionality for exactly this scenario - the details are on the wiki here: http://code.google.com/p/autofac/wiki/DelegateFactories.
In essence, if A needs to create multiple instances of B, A can take a dependency on Func<B> and Autofac will generate an implementation that returns new Bs out of the container.
The other suggestions above are of course valid - Autofac's approach has a couple of differences:
It avoids the need for a large number of factory interfaces
B (the product of the factory) can still have dependencies injected by the container
Hope this helps!
Nick
An IoC takes the responsibility for determining which version of a dependency a given object should use. This is useful for doing things like creating chains of objects that implement an interface as well as having a dependency on that interface (similar to a chain of command or decorator pattern).
By passing your container, you are putting the onus on the individual object to get the appropriate dependency, so it has to know how to. With typical IoC usage, the object only needs to declare that it has a dependency, not think about selecting between multiple available implementations of that dependency.
Service Locator patterns are more difficult to test and it certainly is more difficult to control dependencies, which may lead to more coupling in your system than you really want.
If you really want something like lazy instantiation you may still opt for the Service Locator style (it doesn't kill you straight away and if you stick to the container's interface it is not too hard to test with some mocking framework). Bear in mind, though that the instantiation of a class that doesn't do much (or anything) in the constructor is immensely cheap.
The container's I have come to know (not autofac so far) will let you modify what dependencies should be injected into which instance depending on the state of the system such that even those decisions can be externalized into the configuration of the container.
This can provide you plenty of flexibility without resorting to implementing interaction with the container based on some state you access in the instance consuming dependencies.

Resources