MVVM Dependency Injection - mvvm

I'm in the process of teaching myself the MVVM pattern by dividing the pattern into its core facets and learning those facets one by one.
My question is related to dependency injection. What is it, and why/when should I use it? I've looked at Jason Dolinger's excellent MVVM intro video and I see he uses Unity. This might be strange to ask but how would I implement dependency injection WITHOUT using Unity? I basically want to understand the concept of dependency injection and how to use it without having to implement other frameworks/tools (for now).
Thanks.

I think it's good that you want to understand DI without using a framework, the concept is not terribly difficult to wrap your head around.
Let's say you want to use some form of transportation.
interface ITransportation
{
Transport();
}
An initial implementation of a method that uses a form of transportation might look like this:
public void Move()
{
ITransportation car = new Car();
car.Transport();
}
The problem with that method is that it is now dependent on a Car class. We should pass our transportation object in for added flexibility. This is inversion of control and is closely related to DI.
public void Move(ITransportation tr)
{
tr.Transport();
}
As you can see, we don't need to know anything about a specific DI framework. You might also want to check out the ninject DI by hand tutorial.

Just to extend #Andy's answer
Dependency Injection is one of the forms of the Dependency Inversion Principle
To achieve the decoupling of dependencies (as typically found in layered architecture),
DI is commonly used for instantiation scenarios such as basic new() and patterns like Factory method. In addition to being able to inject a new dependency instance every time (e.g. like factory), containers can also be set up to inject named instances, singleton instances, etc - i.e. IoC containers usually also take on the responsibility of managing the lifespans of objects as well.
One potential 'mindset shift' is that dependencies now potentially become publicly visible on concrete classes, since DI typically injects via constructors or public Get / Set properties. This may seem strange if you are used to using OO encapsulation, where dependencies of a class are seen as implementation and should be hidden from the 'outside' i.e. class method signatures.
However, by implementing Interface / Concrete class separation (as you should, not only for decoupling but also for testing / mocking purposes), the injection constructors / property injection methods will not be on the interface, so encapsulation is again in place.
Re : "Doing DI by hand" without Unity etc
What you would need to do is to code your own IoC container, which then is responsible for 'building up' instances of classes - during each 'build up', you would scan the class for dependencies (which are configured in the container, e.g. by config, by attributes, or simply just by convention, e.g. all public settable properties, or any class parameters on a constructor will be assumed to be dependencies). You would then create (if necessary) and inject this 'dependency' instance onto the object (e.g. by using reflection). And then recursively, all dependencies of these dependencies need to be built up etc. You would then also need to provide lifespan management for each of the objects, e.g. Singletons etc.

Related

Resolve Views through IoC or MEF instead of using SelectedAssemblies() method

I use Caliburn.Micro with Spring.net instead of the default simple IoC. My custom Bootstrapper (derrived from Caliburn's BootstrapperBase) is working and I can define the ViewModels within Spring.net. But the the Views are still resolved by reflection (name convention) from the execution assembly. I used the following method of the Bootstrapper to add Assemblies for resolving the Views for the ViewModels.
protected override IEnumerable<Assembly> SelectAssemblies()
{
// hmm, want to change the way how the view is resolved... how to do this?
// ... use IoC or MEF for this task instead?
return new[]
{
// don't want to add every dll here
this.GetType().Assembly,
Assembly.Load("MyViewModels.Assembly")
};
}
How to change the behaviour of resolving views and using IoC or MEF for this task?
The Problem is that the Bootstrapper has no virtual method to override which resolves a requested view. What is the starting point to change this behaviour? I thought there must exist something like
protected virtual Control ResolveViewForModel(Type modelType) {...}
Thanks for any hints.
First of all, I don't know caliburn.micro so this might be wrong.
Looking at the ViewLocator method LocateTypeForModelType it seems that it asks the AssemblySource for available types which should be checked against the View-naming conventions.
Since all of the above are static classes I suspect there is no way to inherit and override that behaviour. Since they are static, one could just add assemblies to the public observable dictionary - which feels a little bit of a hack and SelectAssemblies seems like the proper way.
However, it seems to me that since there are conventions for resolving Views and ViewModels one could do the same for assemblies which brings us to the question: how do you decide which assemblies to scan for ViewModels/Views.
That strategy can be built into the SelectAssemblies method.
If you want to change how caliburn.micro finds the right views in those assemblies, effectively changing/adding to the exisiting conventions, there is an explanation in their wiki.
To finally answer your question: "Resolve Views through IoC or MEF instead of using SelectedAssemblies() method": Imo this kind of defeats the philosophy of Caliburn.Micro:
Caliburn.Micro uses conventions to resolve views from given assemblies - trying to use an IoC container instead of a name / namespace based convention contradicts that approach.

Best practices for Eclipse 4 DI

I'd like to know what the best practices are for Eclipse 4 dependency injection.
After reading about this subject on the internet, I came up with the following strategy.
requirements
Share the data model of the application (e.g. company, employee, customer, ...) so that framework objects (view parts, handlers, listeners, ...) can access it with as little coupling as possible.
proposed strategy
I've used the lifeCycleURI plugin property to register a handler which is triggered at application startup. Such handler creates an "empty" top-level data model container object and place it into the EclipseContext. It is also discarded when application stops.
All Eclipse framework classes (view parts, handlers) use the classic DI to get such data model object injected.
Button listeners created with the class constructor can't have the data model object injected in them. So I thought they could be created with ContextInjectionFactory.make() to have injection performed. This would couple the class which creates the listener with CIF, but the great advantage is that injection works out of the box.
This is the best solution I've found yet to leverage E4 DI with as little coupling as possible. The weak spot is in my opinion this coupling with CIF. My question would be whether any strategy exist to remove even this coupling, or alternate solutions for the same requirements.
You can create a service class in your project, let's say ModelService.
Add #creatable and #singleton annotations to that class :
#creatable
#singleton
class ModelService{
}
And let DI do its job using following syntax in your parts/handlers/etc ..
#Inject ModelService modelService;
Then you can implement methods in your service like 'createBaseModel()', updateModel() and so on.
This creates a low coupling solution : you can also implement ModelService in a separate plugin and define it as a OSGi service.
for that solution, you can read this Lars Vogel article.

Dependency injection and when to use static classes

Are static classes pretty much always frowned upon, or is there ever a good time to use them?
For example, would it make sense to implement something ubiquitous in your application like security in a static class? You could still use property injection on the static class to change out the implementation, and if you were to use something like MEF to inject the implementation then I would think it wouldn't get in the way of your tests.
I use static classes mainly for stateless helper classes and when I want to create extension methods. I try to avoid static classes that have state because as you mention it can get in the way of the tests.
Let's say you decide to add state to a static class. To test the methods of this class that depend on its state you will have to find a way to change this state during the tests. This means that you have to:
Prepare the state before each test.
Clear the state after each test.
This means that the class will need to offer a way (by means of internal methods or internal property setters) to alter its state which can be dangerous. If you want to create immutable classes or classes that encapsulate completely their implementation details then you will not be able to test them easily (if not at all) and your test might break more often from changes to the implementation. Even with MEF it will not be easy to do this.
Of course static class sometimes offer attractive solutions for problems like logging and,as mentioned in your question, security. In these cases I would go for a static class that delegates all calls to a private readonly field. This way the class of this field can be unit tested normally. You can then test the static class in your integration tests.
By the way have a look at .NET's design guidelines for static classes. It doesn't include anything relevant to your question but it includes valuable advice.

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.

Is there any reason to not use my IoC as a general Settings Repository?

Suppose that the ApplicationSettings class is a general repository of settings that apply to my application such as TimeoutPeriod, DefaultUnitOfMeasure, HistoryWindowSize, etc... And let's say MyClass makes use of one of those settings - DefaultUnitOfMeasure.
My reading of proper use of Inversion of Control Containers - and please correct me if I'm wrong on this - is that you define the dependencies of a class in its constructor:
public class MyClass {
public MyClass(IDataSource ds, UnitOfMeasure default_uom) {...}
}
and then call instantiate your class with something like
var mc = IoC.Container.Resolve<MyClass>();
Where IDataSource has been assigned a concrete implementation and default_uom has been wired up to instantiate from the ApplicationSettings.DefaultUnitOfMeasure property. I've got to wonder however, if all these hoops are really that necessary to jump through. What trouble am I setting myself up for should I do
public class MyClass {
public MyClass(IDataSource ds) {
UnitOfMeasure duom = IoC.Container.Resolve<UnitOfMeasure>("default_uom");
}
}
Yes, many of my classes end up with a dependency on IoC.Container but that is a dependency that most of my classes will have anyways. It seems like I maybe should make full use of it as long as the classes are coupled. Please Agile gurus, tell me where I'm wrong.
IoC.Container.Resolve("default_uom");
I see this as a classic anti-pattern, where you are using the IoC container as a service locater - the key issues that result are:
Your application no longer fails-fast if your container is misconfigured (you'll only know about it the first time it tries to resolve that particular service in code, which might not occur except for a specific set of logic/circumstances).
Harder to test - not impossible of course, but you either have to create a real (and semi-configured) instance of the windsor container for your tests or inject the singleton with a mock of IWindsorContainer - this adds a lot of friction to testing, compared to just being able to pass the mock/stub services directly into your class under test via constructors/properties.
Harder to maintain this kind of application (configuration isn't centralized in one location)
Violates a number of other software development principles (DRY, SOC etc.)
The concerning part of your original statement is the implication that most of your classes will have a dependency on your IoC singleton - if they're getting all the services injected in via constructors/dependencies then having some tight coupling to IoC should be the exception to the rule - In general the only time I take a dependency on the container is when I'm doing something tricky i.e. trying to avoid a circular dependency problems, or wish to create components at run-time for some reason, and even then I can often avoid taking a dependency on anything more then a generic IServiceProvider interface, allowing me to swap in a home-bake IoC or service locater implementation if I need to reuse the components in an environment outside of the original project.
I usually don't have many classes depending on my IoC container. I usually try to wrap the IoC stuff in a facade object that I inject into other classes, usually most of my IoC injection is done only in the higher layers of my application though.
If you do things your way you can't test MyClass without creating a IoC configuration for your tests. This will make your tests harder to maintain.
Another problem is that you're going to have powerusers of your software who want to change the configuration editing your IoC config files. This is something I'd want to avoid. You could split up your IoC config into a normal config file and the IoC specific stuff. But then you could just as well use the normal .Net config functionality to read the configuration.
Yes, many of my classes end up with a dependency on IoC.Container but that is a dependency that most of my classes will have anyways.
I think this is the crux of the issue. If in fact most of your classes are coupled to the IoC container itself chances are you need to rethink your design.
Generally speaking your app should only refer to the container class directly once during the bootstrapping. After you have that first hook into the container the rest of the object graph should be entirely managed by the container and all of those objects should be oblivious to the fact that they were created by an IoC container.
To comment on your specific example:
public class MyClass {
public MyClass(IDataSource ds) {
UnitOfMeasure duom = IoC.Container.Resolve<UnitOfMeasure>("default_uom");
}
}
This makes it harder to re-use your class. More specifically it makes it harder to instantiate your class outside of the narrow usage pattern you are confining it to. One of the most common places this will manifest itself is when trying to test your class. It's much easier to test that class if the UnitOfMeasure can be passed to the constructor directly.
Also, your choice of name for the UOM instance ("default_uom") implies that the value could be overridden, depending on the usage of the class. In that case, you would not want to "hard-code" the value in the constructor like that.
Using the constructor injection pattern does not make your class dependent on the IoC, just the opposite it gives clients the option to use the IoC or not.