Where to register observers when using IoC containers? - inversion-of-control

In my current application, I am using a 'selfmade' Observable class in order to implement the observer pattern. Observers (implementing an interface) can listen to certain events.
I am switching more and more of the project over to using an IoC container, but I fail to find a good place in the code to register the observers with the observable.
The ways to do this that I see are:
A) Inject the observable into the observer.
The constructor shouldn't do actual work, but even with method- or field injection this couples the observer with the observable. This is also the case if it's the other way around.
B) Create an observable factory and do it there.
In this case creating the observable depends on the implementations of several observers.
C) Create the observers by factory and do it there.
While this seems best to me concerning coupling, it turns out bad concerning DRY. In some cases the factory ends up being a copy of the fields and constructor of the observer, plus the observable and plus the one line of code for the registering.
Is there a way to handle this registering in a clean way? If not, are there compelling arguments to use a certain way over the others?

The solution was discovering the difference between Resolve() and Instantiate() methods.
I was always using Resolve(). With that, I would receive an Observer in the way it has been bound to the container.
However, Instantiate() does not care about how the class is bound to the container. It creates the class the standard way, but still injects the dependencies. So this can be used inside the factory for the observer.

Related

Scala: Making singleton to process a client request

Is it a good practice to make use of singleton object to process client requests?
As object instance is singleton, and if its in middle of processing a client request , and meanwhile another request arrives then same instance is invoked with new client data. Won't it make things messy?
When using singleton objects we must ensure everything inside it as well as everything it calls must be thread-safe. For example, javax.crypto.Cipher does not seem to be thread-safe, so it should probably not be called from a singleton. Consider how guice uses #Singleton to specify threadsafety intention:
#Singleton
public class InMemoryTransactionLog implements TransactionLog {
/* everything here should be threadsafe! */
}
Also consider the example of Play Framework which starting version 2.4 began moving away from singleton controllers and started encouraging class controllers.
It depends on whether the object holds any mutable data or not.
If the object is just a holder for pure functions and immutable state, it does not matter how many threads are using it at the same time because they can't affect each other via shared state.
If the object has mutable state then things can definitely go wrong if you access it from multiple threads without some kind of locking, either inside the object or externally.
So it is good practice as long as there is no mutable state. It is a good way of collecting related methods under the same namespace, or for creating a global function (by defining an apply method).

rxjava 2.0 what is the difference between Observable.subscribe and Observable.subscribeActual?

The documentation just says
protected abstract void subscribeActual(Observer<? super T> observer)
Operator implementations (both source and intermediate) should implement this method that performs the necessary business logic.
There is no need to call any of the plugin hooks on the current Observable instance or the Subscriber.
Observable.subscribe comes from the base interface definition in ObservableSource and is the main subscription method for Observables: internal and external components use it to run a flow in a standard way.
However, certain actions may be necessary for all kinds of Observables to be executed before the operator's business logic gains access to the incoming Observer, for example, applying plugin hooks and protecting against crashing subscribe implementations. So instead of requiring every operator to duplicate this preparation logic, they are in a single place and a new abstract method is present to deal with the customization of an Observable.

Should a ViewModel be initialized via constructor, properties, or method call

I'm fighting a few different design concepts within the context of MVVM that mainly stem from the question of when to initialize a ViewModel. To be more specific in terms of "initializing" I'm referring to loading values such as selection values, security context, and other things that could in some cases cause a few second delay.
Possible strategies:
Pass arguments to ViewModel constructor and do loading in the constructor.
Only support a parameterless constructor on the ViewModel and instead support initialize methods that take parameters and do the loading.
A combination of option 1 and 2 where arguments are passed to the ViewModel constructor but loading is deferred until the an Initialize method is called.
A variation on option 3 where instead of parameters being passed to the ViewModel constructor they are set directly on properties.
Affect on ViewModel property getters and setters
In cases where initialization is deferred there is a need to know whether the ViewModel is in a state that is considered available for which the IsBusy property generally serves just as it does for other async and time consuming operations. What this also means though is that since most properties on the ViewModel expose values retrieved from a model object that we constantly have to write the following type of plumbing to make sure the model is available.
public string Name
{
get
{
if (_customerModel == null) // Check model availability
{
return string.Empty;
}
_customerModel.Name;
}
}
Although the check is simple it just adds to the plumbing of INPC and others types of necessities that make the ViewModel become somewhat cumbersome to write and maintain. In some cases it becomes even more problematic since there may not always be a reasonable default to return from the property getter such might be the case with a boolean property IsCommercialAccount where if there is no model available it doesn't make sense to return true or false bringing into question a whole slew of other design questions such as nullability. In the case of option 1 from above where we passed everything into the constructor and loaded it then we only need to concern ourselves with a NULL ViewModel from the View and when the ViewModel is not null it is guaranteed to be initialized.
Support for deferred initialization
With option 4 it is also possible to rely on ISupportInitialize which could be implemented in the base class of the ViewModel to provide a consistent way of signaling whether the ViewModel is initialized or not and also to kick off the initialization via a standard method BeginInit. This could also be used in the case of option 2 and 3 but makes less sense if all initialization parameters are set all in one atomic transaction. At least in this way, the condition shown above could turn into something like
How the design affects IoC
In terms of IoC I understand that options 1 and 3 can be done using constructor injection which is generally preferred, and that options 2 and 4 can be accomplished using method and property injection respectively. My concern however is not with IoC or how to pass in these parameters but rather the overall design and how it affects the ViewModel implementation and it's public interface although I'd like to be a good citizen to make IoC a bit easier if necessary in the future.
Testability
All three options seem to support the concept of testability equally which doesn't help much in deciding between these options although it's arguable that option 4 could require a more broad set of tests to ensure proper behavior of properties where that behavior depends on the initialization state.
Command-ability
Options 2, 3, and 4 all have the side effect of requiring code behind in the View to call initialization methods on the ViewModel however these could be exposed as commands if necessary. In most cases one would probably be loading calling these methods directly after construction anyways like below.
var viewModel = new MyViewModel();
this.DataContext = viewModel;
// Wrap in an async call if necessary
Task.Factory.StartNew(() => viewModel.InitializeWithAccountNumber(accountNumber));
Some other thoughts
I've tried variations on these strategies as I've been working with the MVVM design pattern but haven't concluded on a best practice yet. I would love to hear what the community thinks and attempt to find a reasonable consensus on the best way forward for initializing ViewModels or otherwise dealing with their properties when they are in an unavailable state.
An ideal case may be to use the State pattern where the ViewModel itself is swapped out with different ViewModel objects that represent the different states. As such we could have a general BusyViewModel implementation that represents the busy state which removes one of the needs for the IsBusy property on the ViewModel and then when the next ViewModel is ready it is swapped out on the View allowing that ViewModel to follow the stategy outlined in option 1 where it is fully initialized during construction. This leaves open some questions about who is responsible for managing the state transitions, it could for example be the responsibility of BusyViewModel to abstract something similar to a BackgroundWorker or a Task that is doing the initialization itself and will present the internal ViewModel when ready. Swapping the DataContext on the view on the other hand may require either handling an event in the View or giving limited access to the DataContext property of the View to BusyViewModel so it can be set in the traditional state pattern sense. If there is something similar that people are doing along these lines I would definitely like to know because my google searching hasn't turned up much yet.
My general approach to object oriented design, whether I am creating a view model, or an other type of class is that; Everything that can be passed to the constructor, should be passed to the constructor. This reduces the need to have some sort of IsInitialized state and makes your objects less complex. Sometimes certain frameworks make it hard to follow this approach, IoC containers for example (although they should allow constructor injection), but I still adhere to it as a general rule.

IoC (StructureMap) Best Practice

By my (likely meager) understanding, doing this in the middle of a method in your controller / presenter is considered bad practice, since it creates a dependency between StructureMap and your presenter:
void Override() {
ICommentForOverrideGetter comm = StructureMap.ObjectFactory.GetInstance<ICommentForOverrideGetter>();
since this dependancy should be injected into the presenter via the constructor, with your IoC container wiring it up. In this case though my code needs a fresh copy of ICommentForOverrideGetter every time this method runs. Is this an exception to the above best practice, or a case where I should re-think my architecture?
It is said that there is no problem in computer science which cannot be solved by one more level of indirection:
If you just don't want the dependency in your presenter, inject a factory interface, the real implementation could do new CommentForOverrideGetter or whatever.
Edit:
"I have no problem ignoring best practices when I think the complexity/benefit ratio is too high": Neither do I, but as I said in the comments, I don't like hard dependencies on IoC containers in code I want to unit test and presenters are such a case.
Depending on what your ICommentForOverrideGetter does, you could also use a simple CommentForOverrideGetter.CreateNew() but as you require a fresh instance per call, I'd suspect at least some kind of logic associated with the creation? Or is it a stateful "service"?
If you insist on doing service location in your method, you should at least inject the container into your controller, so that you can eliminate the static method call. Add a constructor parameter of type StructureMap.IContainer and store it in a field variable. StructureMap will inject the proper container. You can then call GetInstance() on that container, instead of ObjectFactory.

ServiceContainer, IoC, and disposable objects

I have a question, and I'm going to tag this subjective since that's what I think it evolves into, more of a discussion. I'm hoping for some good ideas or some thought-provokers. I apologize for the long-winded question but you need to know the context.
The question is basically:
How do you deal with concrete types in relation to IoC containers? Specifically, who is responsible for disposing them, if they require disposal, and how does that knowledge get propagated out to the calling code?
Do you require them to be IDisposable? If not, is that code future-proof, or is the rule that you cannot use disposable objects? If you enforce IDisposable-requirements on interfaces and concrete types to be future-proof, whose responsibility is objects injected as part of constructor calls?
Edit: I accepted the answer by #Chris Ballard since it's the closest one to the approach we ended up with.
Basically, we always return a type that looks like this:
public interface IService<T> : IDisposable
where T: class
{
T Instance { get; }
Boolean Success { get; }
String FailureMessage { get; } // in case Success=false
}
We then return an object implementing this interface back from both .Resolve and .TryResolve, so that what we get in the calling code is always the same type.
Now, the object implementing this interface, IService<T> is IDisposable, and should always be disposed of. It's not up to the programmer that resolves a service to decide whether the IService<T> object should be disposed or not.
However, and this is the crucial part, whether the service instance should be disposed or not, that knowledge is baked into the object implementing IService<T>, so if it's a factory-scoped service (ie. each call to Resolve ends up with a new service instance), then the service instance will be disposed when the IService<T> object is disposed.
This also made it possible to support other special scopes, like pooling. We can now say that we want minimum 2 service instances, maximum 15, and typically 5, which means that each call to .Resolve will either retrieve a service instance from a pool of available objects, or construct a new one. And then, when the IService<T> object that holds the pooled service is disposed of, the service instance is released back into its pool.
Sure, this made all code look like this:
using (var service = ServiceContainer.Global.Resolve<ISomeService>())
{
service.Instance.DoSomething();
}
but it's a clean approach, and it has the same syntax regardless of the type of service or concrete object in use, so we chose that as an acceptable solution.
Original question follows, for posterity
Long-winded question comes here:
We have a IoC container that we use, and recently we discovered what amounts to a problem.
In non-IoC code, when we wanted to use, say, a file, we used a class like this:
using (Stream stream = new FileStream(...))
{
...
}
There was no question as to whether this class was something that held a limited resource or not, since we knew that files had to be closed, and the class itself implemented IDisposable. The rule is simply that every class we construct an object of, that implements IDisposable, has to be disposed of. No questions asked. It's not up to the user of this class to decide if calling Dispose is optional or not.
Ok, so on to the first step towards the IoC container. Let's assume we don't want the code to talk directly to the file, but instead go through one layer of indirection. Let's call this class a BinaryDataProvider for this example. Internally, the class is using a stream, which is still a disposable object, so the above code would be changed to:
using (BinaryDataProvider provider = new BinaryDataProvider(...))
{
...
}
This doesn't change much. The knowledge that the class implements IDisposable is still here, no questions asked, we need to call Dispose.
But, let's assume that we have classes that provide data that right now doesn't use any such limited resources.
The above code could then be written as:
BinaryDataProvider provider = new BinaryDataProvider();
...
OK, so far so good, but here comes the meat of the question. Let's assume we want to use an IoC container to inject this provider instead of depending on a specific concrete type.
The code would then be:
IBinaryDataProvider provider =
ServiceContainer.Global.Resolve<IBinaryDataProvider>();
...
Note that I assume there is an independent interface available that we can access the object through.
With the above change, what if we later on want to use an object that really should be disposed of? None of the existing code that resolves that interface is written to dispose of the object, so what now?
The way we see it, we have to pick one solution:
Implement runtime checking that checks that if a concrete type that is being registered implements IDisposable, require that the interface it is exposed through also implements IDisposable. This is not a good solution
Enfore a constraint on the interfaces being used, they must always inherit from IDisposable, in order to be future-proof
Enforce runtime that no concrete types can be IDisposable, since this is specifically not handled by the code using the IoC container
Just leave it up to the programmer to check if the object implements IDisposable and "do the right thing"?
Are there others?
Also, what about injecting objects in constructors? Our container, and some of the other containers we've looked into, is capable of injecting a fresh object into a parameter to a constructor of a concrete type. For instance, if our BinaryDataProvider need an object that implements the ILogging interface, if we enforce IDispose-"ability" on these objects, whose responsibility is it to dispose of the logging object?
What do you think? I want opinions, good and bad.
One option might be to go with a factory pattern, so that the objects created directly by the IoC container never need to be disposed themselves, eg
IBinaryDataProviderFactory factory =
ServiceContainer.Global.Resolve<IBinaryDataProviderFactory>();
using(IBinaryDataProvider provider = factory.CreateProvider())
{
...
}
Downside is added complexity, but it does mean that the container never creates anything which the developer is supposed to dispose of - it is always explicit code which does this.
If you really want to make it obvious, the factory method could be named something like CreateDisposableProvider().
(Disclaimer: I'm answering this based on java stuff. Although I program C# I haven't proxied anything in C# but I know it's possible. Sorry about the java terminology)
You could let the IoC framework inspect the object being constructed to see if it supports
IDisposable. If not, you could use a dynamic proxy to wrap the actual object that the IoC framework provides to the client code. This dynamic proxy could implement IDisposable, so that you'd always deliver a IDisposable to the client. As long as you're working with interfaces that should be fairly simple ?
Then you'd just have the problem of communicating to the developer when the object is an IDisposable. I'm not really sure how this'd be done in a nice manner.
You actually came up with a very dirty solution: your IService contract violates the SRP, wich is a big no-no.
What I recommend is to distinguish so-called "singleton" services from so-called "prototype" services. Lifetime of "singleton" ones is managed by the container, which may query at runtime whether a particular instance implements IDisposable and invoke Dispose() on shutdown if so.
Managing prototypes, on the other hand, is totally the responsibility of the calling code.