How to create two configured instances of the same service? - grails

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.

Related

How to denote component lifetime when using convention-based registration?

I've read a lot on the subject of IoC containers and particularly Mark Seemann's blog posts, where he emphasises the importance of convention over configuration. I understand and agree with his point, but I wonder how best to mark out a class for an irregular lifetime?
For example, most of my services are registered with a Transient lifetime - but I want a particular service to be registered as a Singleton because it does some useful caching.
I have thought about using some custom attributes, but I have read arguments against this (because it puts composition logic in the class).
I have had this same debate with, for example, dependencies on configuration primitives. Ultimately I ended up using a parameter attribute because it worked in my case, but I feel that perhaps I didn't see the 'hidden dangers'.
It is common for an IoC container to allow you to specify the lifestyle of an object. SimpleInjector, for example, provides Transient and Singleton out of the box (and also allows the user to create a custom lifestyle class). With SimpleInjector it's as simple as:
container.Register<ISvc, Impl>(Lifestyle.Singleton);
or
container.Register<ISvc, Impl>(Lifestyle.Transient);
No need for polluting your classes with composition logic.
As for configuration primitives, a common practice is to put those behind an interface. I put my connection string behind an IDatabaseConfiguration interface, for example, and its implementation reads the value from web.config. I then inject that interface into my data services.
EDIT: Disregard above. Keeping it in so that comments make sense.
The following doesn't actually answer the question, but it may solve the problem that prompted the question. You said that the class does some useful caching, which clues me in on that it is taking on an additional responsibility. I would therefore recommend that you do not attempt to register that single implementation as a singleton, but instead create a decorator class around that implementation.
container.RegisterDecorator(
typeof(ICommandHandler<>),
typeof(CommandHandlerCacheDecorator<>),
Lifestyle.Transient,
x => { return /*some logic that looks for and
finds that one class you want
to decorate*/
});
The decorator needs to be a transient, because it will have a transient reference to the command it decorates. However, it could then access a separate singleton class (via dependency injection of course) or cache object that handles the actual caching.
EDIT: Examples to single out the one class to decorate. There are plenty of options depending on just how specific you want to be. Again this is with SimpleInjector, but I'm sure other containers have their own analogues.
//decorate a specific class
x => { return x.ImplementationType.FullName == "My.Commands.Web.SomeName"; }
//decorate all classes that share a certain namespace
x => { return x.ImplementationType.Namespace.EndsWith("Commands.Web"); }
//decorate all classes that implement the same interface
x => { return x.ImplementationType.IsInstanceOfType(typeof(ICouldCache)); }

How can I manage multiples modules using IOC Containers

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.

Object lifecycle management and IoC containers

I'm updating a game from single player to multiplayer. In this case the game was originally written with most classes being single instanced. e.g. there was a single Player object, a single GameState object, etc. That is, each of these objects lived as long as the application.
Now that more than one player can play at once I obviously need to support creating more than one Player object, GameState object, etc. Over the course of working on this I have come to realize that most objects have one of three lifespans:
App's lifespan, e.g. a Conductor to handle navigation
Player's lifespan, e.g. the SettingsViewModel for the current player
Game's lifespan, e.g. the GameState for the current game
I'm curious how others deal with the creation of these different objects using an IoC container. I want to avoid creating factory classes for each class with a player or game lifespan.
Here is an example of IOC that may help. The project is called IOC-with-Ninject. It uses Ninject plus an IOC container class to manage all object life spans. You will need to do a little research on Ninject to customize it to your specific needs, but this is your IOC container solution (IMHO) if you are using .NET and will help you organize your code base. This is a personal choice, but I swear by it. If you are not using .NET it will still give you an easy pattern to follow. Cheers.
Many IoC containers have custom life-cycle scopes which you can manage as your wish. For example in Ninject you can define your custom life cycle scope as follows:
kernel.Bind<IService>().To<Service>().InScope((c, o) => yourCustomeScope);
As long as the yourCustomeScope variable has not changed, one single instance of the Service object is returned each time the kernel receives a request for IService. As soon as the yourCustomeScope variable changes, a new instance of Service will be created on the next request for IService. yourCustomeScope can be the current player instance, the game object or anything that you want to change the lifetime of the Service object, based on its reference change.
However, the objects that you just mentioned are more likely to be entities rather than services for which I don't think injection is a good idea.
From my experience the factories approach works the best.
Controlling lifespan of instance is clunky for support and requires efforts, knowledge of all of the classes lifespan requirements and dependencies, time for configuration and management of the configuration. In same time the use of factories is natural and code specific.
Factories (implementation) creation might be avoided by using proxy factories . You can also have factories returning generic arguments to further decrease the needs of factories (interfaces) creation.
If still too many factories are required I suggest reviewing the code flow.
I think this is in part a rehash of some of the comments of the previous answers but I have tried to exemplify expand a little on some of the reasoning.
Once you get into the domain of managing injected objects lifespan, you probably should be creating factories for these objects.
The underlying problem is that the composition root is not aware of what the environmental context of the call will be that needs to create the object.
I think I should take a step back and explain at this point.
Received wisdom on dependancy injection is to have a composition root some where near the entry point of the code. There are many good reasons for this that are not difficult to find on the web so I won't go into that here.
The composition root is where you map your interfaces (usually, but possibly objects) to their implmentations. You can pass in information that is available at this point to the constructor. So you can pass in a reference to an object whose lifetime is current at the time of execution of the composition root.
However, if the lifetime of the composition root does not overlap with the life time of the object you want to create you have to defer the execution of the constructor until the object needs to be created. This is why you need to have a factory. You can pass a factory method in to your mapping at this point and thus pass in the information needed to generate the object, but allow the creation to happen at the time it is required not when the composition root is executed.
You do not need a factory class to do this factory methods are fine, moreover the factory method can be inlined and so the code overhead is not much more than if we were creating the objects in the composition route.
If we have a project with 2 services where the first service is dependant on the first and we only want the lifetime of the second service to start when we create the first service we might have something like the following. (I am using ninject to give a code example, but I expect that other IOC containers work similarly in this respect.)
`
public class Service1:IService
{
private Func<IService>serviceFactoryMethod _Service2Factory;
public Service1(Func<IService>service2FactoryMethod)
{
_Service2Factory=service2FactoryMethod;
}
public void DoSomethingUsingService2()
{
var service2=_Service2Factory();
service2.DoSomething();
}
}
public class MainClass
{
public void CompositionRoot()
{
var kernel= new StandardKernel();
kernel.Bind.ToMethod(m=>
{
return new Service1(m.Kernel.Get<IService2>());
}
}
}
`
This example does not address how you would manage the lifetime of the App, players and games lifespans, but hopefully it gives sufficient clues as to how to remove lifetime issues related to dependancy injection.
Side note: that using Ninject you would be able to change the scope of Service2 in order to manage its lifetime to go beoynd the lifetime of Service1. For example, if you knew each instance of a game were to happen on its own thread (OK, this maybe somewhat unlikely), you might use InThreadScope for the game.

DI: Register-Resolve-Release when using child containers

There's this software, X, which has this really complicated API that I have to write a facade for. I wrote a class library, XClientLibrary, and I made it using DI and IoC container (Unity). This was possible because my library exports services (interfaces) so users are not aware of the concrete classes which use constructor DI. They're also unaware of the IoC container.
The "root service" is a IXClient instance which is supposed to be created once and used as long as the application runs. (It is a desktop application btw). The X-client allows users to connect to X-hosts if they know the URL. A X-host allows users to access host's services and their services and so on (quite a complex object graph). This is sample user code:
// 1. app startup
XClientProvider provider = new XClientProvider(); // call only once per app
IXClient xClient = provider.GetClient(); // always returns the same instance
xClient.Startup();
// 2. app normal usage
IXHost host = xClient.ConnectToHost(new Uri("http://localhost")); // return new instance each time
IXService1 service = host.GetThis();
IXService2 otherService = service.DoThat();
...
host.Dispose();
// get another host, consume it, dispose it, etc
...
// 3. app shutdown
xClient.Shutdown();
provider.Dispose();
I tried to follow Mark Seemann's suggestions to implement this, but I'm not sure if they apply to a class library too. The client provider is the composition root, which is the only place where the IoC container is used. The composition root follows the RRR pattern:
the container is created on new XClientProvider() and configured
the container resolves IXClient when calling GetClient()
the container is disposed on provider.Dispose()
Things get complicated when the container is asked to resolve IXHost. Its implementation is:
internal class XHost : IXHost
public XHost(Uri uri, IXService1 service1)
The client is supposed to create XHost instances, so its implementation needs to know how to create IXService1:
internal class XClient : IXClient
public XClient(Func<IXService1> xService1DelegateFactory)
Invoking the delegate factory reaches the container which creates a IXService1. Also, let's say that in this graph there is a class XComponent7 which requires the exact IXService1 instance which was used to create the host:
internal class XComponent7 : IXService7
public XComponent7(Func<IXService1> service1DelegateFactory)
I have to use Func to deal with the circular dependency. The container should be configured such that once a IXService1 was resolved, it will provide the same instance whenever asked to resolve IXService1.
Now it gets really complicated. I want to restrict this behavior "per host resolve", meaning once a host is created the container should create a IXService1 and cache it and provide it to whatever component needs it, as long as the component is part of the object graph of the host. I also need a way to dispose all components when a host is disposed.
I was thinking I can do it using child containers. I can create one when users call ConnectToHost, ask it to resolve the host and dispose it on host disposal. The main container is still alive and won't be disposed until they call Dispose on the provider.
Problem is, I think it breaks the RRR pattern. So I wonder how RRR works when child container are involved... Maybe the IXHost is another "root" which can be directly resolved by the composition root? Or maybe there's a really smart Unity lifetime manager which can do what I need?
#Suiden So my understanding is: Your client is something that lets you lookup hosts (like a registry). Hosts offer services implemented by components. Every application has exactly one instance of your lookup/client. Your components not only implement services but might need other services to do their job. You want to resolve all parts of that object graph exactly once and when you dispose your client throw all of it away.
A couple of thoughts:
Circular references between dependencies (or services) is something you should try to avoid. If these services need each other that indicates they should be one service. That's what high cohesion, low coupling is about.
Unity does not clean up after itself. That means that even if you dispose a container that will not dispose the objects created by that container. The cleanup feature is on the wish list for Unity vNext
If you want to resolve an instance of some service and cache that instance inside your client/host wherever you should have a look at Lazy. It takes a Func to create an instance of T and evaluates that Func the first time the value is requested. So you can inject the Func into your classes or teach Unity to inject Lazy instances directly.
Child containers are a feature I find less than usefull. You can scope registration information and object lifetimes. But to make use of these scopes you would have to reference the appropriate child container. That means you are dropping dependency injection in favor of the ServiceLocator anti-pattern.

Inversion of control domain objects construction problem

As I understand IoC-container is helpful in creation of application-level objects like services and factories. But domain-level objects should be created manually.
Spring's manual tells us: "Typically one does not configure fine-grained domain objects in the container, because it is usually the responsibility of DAOs and business logic to create/load domain objects."
Well. But what if my domain "fine-grained" object depends on some application-level object.
For example I have an UserViewer(User user, UserConstants constants) class.
There user is domain object which cannot be injected, but UserViewer also needs UserConstants which is high-level object injected by IoC-container.
I want to inject UserConstants from the IoC-container, but I also need a transient runtime parameter User here.
What is wrong with the design?
Thanks in advance!
UPDATE
It seems I was not precise enough with my question. What I really need is an example how to do this:
create instance of class UserViewer(User user, UserService service), where user is passed as the parameter and service is injected from IoC.
If I inject UserViewer viewer then how do I pass user to it?
If I create UserViewer viewer manually then how do I pass service to it?
there's nothing wrong with this design. you use Factories for that, which have one leg in the domain, one leg in infrastructure.
You can either write them manually, or have the container do that for you, by things like TypedFactoryFacility in Windsor.
Also when your domain objects come from persistence layer you can plug your container there to inject the services they require (NHibernate can do that).
But what if my domain "fine-grained" object depends on some application-level object?
It is precisely this that is considered bad-practice. I would say the problems could be:
There are tons of these objects, so there can be performance and memory issues.
The POJO style is that they can be used in all environments (persisted in the database, processed in business algorithms and rules, read and set in view technologies, serialized and send over the network). Injecting application-level objects in them could cause the following problems:
In your architecture, you probably have the rule that some (most) application-level objects are usable in some layers, not in others. Because all layers have access to the pojos, the rule would be violated transitively.
When serialized and rebuild in another JVM, what would be the meaning of your application-level objects. They are useless, they must be changed for the local equivalents...
Typically, the pojos that constitute your domain are self-contained. They can have access to other pojos (and many enums), that's all.
In addition to the data, they have methods that implement the details of the business rules or algorithms (remember the OO idea of grouping data and code that work on it ;-) ):
This is especially good when they have inheritance, as this allow to customize a business rule for some pojo by providing a different implementation (differing case without if or switch: remember OO? ;-) ).
Any code that requires access to application-level objects (like accessing the database) is taken out, for example to a Service or Manager. But that code stays high level, thus readable and simple, because the pojos themselves take care of the low level details (and the special cases).
After the fact, you often find out that the pojo methods get reused a lot, and composed in different ways by the Services or Managers. That's a big win on reducing duplication, the methods names provide much needed "meaning", and provide an easier access to developers that are new to a module.
For your update:
create instance of class UserViewer(User user, UserService service), where user is passed as the parameter and service is injected from IoC.
If I inject UserViewer viewer then how do I pass user to it?
If I create UserViewer viewer manually then how do I pass service to it?
In that case, you need a factory method (possibly on a Factory or Locator of yours). It could look at follow, separating the two parts:
public UserViewer createUserViewer(User user) {
UserViewer viewer = instantiateBean(UserViewer.class);
viewer.setUser(user);
return viewer;
}
private <E> E instantiateBean(Class<E> clazz) {
// call the IoC container to create and inject a bean
}

Resources