Castle Windsor constructor injection in WPF ViewModel - c#

I am trying to avoid the anti-pattern of Container.Resolve(). How do I change the following to use contructor injection?
Installers.cs
public void Install(Castle.Windsor.IWindsorContainer container,
Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
{
container.AddFacility<TypedFactoryFacility>();
container
.Register(Component.For<IData>()
.ImplementedBy<Data>().LifeStyle.Singleton)
}
BootStrapper.cs
public class Bootstrapper
{
private static volatile IWindsorContainer _theWindsorContainer;
private static object syncRoot = new Object();
public static IWindsorContainer Container
{
get
{
if (_theWindsorContainer == null)
{
lock (syncRoot)
{
if (_theWindsorContainer == null)
{
_theWindsorContainer = new WindsorContainer().Install(FromAssembly.This());
}
}
}
return _theWindsorContainer;
}
}
}
OViewModel.cs
public IData ThisData {get;set;}
public OViewModel()
{
ThisData= Bootstrapper.Container.Resolve<IData>();
InitializeComponent();
}
How do I use Windsor Castle constructor injection to initialize the viewmodel and do constructor injection? Either InitializeComponentdoesn't get called or ThisData is null.

I wrote an article a few years ago about integrating Castle Windsor into WPF to achieve DI in your view models. It might be what you're looking for.

I'm not familiar with the particulars of Castle Windsor, but typically you would structure your OViewModel like this:
public class OViewModel
{
public IData ThisData { get; set; } //private set??
public OViewModel(IData _thisData)
{
ThisData = _thisData;
InitializeComponent();
}
}
That would be constructor injection. You can search for the term parameter injection for other ways of getting it done.
But basically the when an OViewModel is resolved by the container, it knows how to resolve an IData and will automatically resolve it for you.
Of course, this just backs things up -- whatever is creating the OViewModel needs to use container.Resolve and you don't want to do that. So you'll probably inject the view model (or an interface of it) (or a factory object) to that parent object. And so on back up the chain until you have single object that is the root of your application that you need to resolve from the container to get everything started.
Hopefully someone with more knowledge of the particulars of Castle Windsor can give you more details.

Related

How to inject instance with [Dependency] attribute using Unity?

I am using Unity for dependency injection in ASP.NET C#.
Normally I would inject dependencies in the constructor, like:
class MyClass
{
private readonly ISomething _something;
public MyClass(ISomething something)
{
_something = something;
}
public MyMethod()
{
// _something is instantiated as expected
}
}
where the dependency has been configured as:
container.RegisterType<ISomething, Something>();
That's all great.
But now I need to do an injection without the use a constructor. So I read that I can use the dependency attribute [Dependency] for this purpose.
class MyClass
{
[Dependency]
private ISomething _something { get; set; }
public MyMethod()
{
// _something appears to be null
}
}
But for some reason _something appears to be null.
What am I missing?
SOLUTION:
See the accepted answer over here, which shows how to create a factory to generate the injected instance:
How to resolve dependency in static class with Unity?
Worked for me!
You are trying to inject into a private property. This is not possible.
And personally, I suggest you stick to constructor injections to prevent locking yourself into a specific Dependency Injection framework.

Castle windsor resolution pipeline with Unity as sub resolver

Shortly speaking I am trying to link Castle Windsor container with Unitycontainer. Let me explain the context:
I have a project in which for very long time it used castle windsor. A few days ago, I got a bunch of dll's that I must consume / use from my old project. Those DLL's use Unity Container as their injection mechanism. I also have access to interfaces / implementations that are found in those dlls but I would not try to instantiate manually implementations but I would just prefer, if possible, to link the Unity container with my current castle windsor container. How could I achieve this?
So if I have:
public class MyService: IService
{
public MyService (IThidPartyService thirdParty)
{
}
}
If I resolve IService with windsor it would be nice that IThirdPartyService to be solved by the other container: Unity.
Thank you!.
I think this is a perfect example for the use of a custom ISubDependencyResolver. Whenever Castle won't know how to resolve a specific dependency it will address that custom resolver. That new resolver will depend on the Unity Container and will use it to resolve "for" Castle.
Castle's documentation states that:
If previous places weren't able to resolve the dependency resolver
will ask each of its sub resolvers (ISubDependencyResolver) if they
can provide the dependency.
So when that dependency will not be found in Castle it will seek your new resolver which will provide the dependency.
Here is a working example with both Constructor Injection and Property Injection:
class Program
{
static void Main(string[] args)
{
var unityContainer = new UnityContainer();
unityContainer.RegisterType<IDependency, Dependency1>();
unityContainer.RegisterType<IPropertyDependency, PropertyDependency1>();
WindsorContainer castleContainer = new WindsorContainer();
castleContainer.Kernel.Resolver.AddSubResolver(new UnityResolver(unityContainer));
castleContainer.Register(
Component.For<SomeType>());
var result = castleContainer.Resolve<SomeType>();
}
}
public interface IDependency { void Foo(); }
public class Dependency1 : IDependency { public void Foo() { } }
public interface IPropertyDependency { }
public class PropertyDependency1 : IPropertyDependency { }
public class SomeType
{
public SomeType(IDependency dependency) { ConstructorDependency = dependency; }
public IDependency ConstructorDependency { get; private set; }
public IPropertyDependency PropertyDependency { get; set; }
}
public class UnityResolver : ISubDependencyResolver
{
public UnityResolver(UnityContainer container)
{
Container = container;
}
public bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
{
return Container.Registrations.Any(z => z.RegisteredType.Equals(dependency.TargetType));
}
public object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
{
return Container.Resolve(dependency.TargetType);
}
public UnityContainer Container { get; set; }
}
And the result:
As for the code for checking Unity for the CanResolve - I'm sure it can be improved - I do not know much about Unity

The right way to do property dependency injection using Unity

I have a class that needs a dependency injecting. As the class is already an implementation of another abstraction, and its 'sibling' implementations may not share the same dependencies, I am attempting to use property injection and not constructor injection.
(All these classes/interface names are just for illustrative purposes)
My IProvider abstraction:
public interface IProvider
{
void ProviderMethod();
}
My IProvider implementation (with the IData dependency I want to inject):
public class ProviderClass : IProvider
{
// How do I inject this dependency?
[Dependency]
public IData data { get; set; }
public void ProviderMethod()
{
// Can't do this as data == null!
data.DataMethod();
}
}
Another IProvider implementation (example to show that it doesn't have the same dependencies):
public class AnotherProviderClass : IProvider
{
// No data dependency here!!
public void ProviderMethod()
{
// Do other stuff here
}
}
Example IData abstraction and implementation:
public interface IData
{
void DataMethod();
}
public class DataClass : IData
{
public void DataMethod();
}
What I need to know is: How do I successfully inject the property dependency (IData) into ProviderClass using Unity (my IOC container of choice)?
I have tried all manner of Unity registering options (RegisterType, RegisterInstance, Resolve...) but my injected property always ends up as NULL. I want to do this right and not just force random code in until it just manages to work.
Or is there a better way of injecting (optional) dependencies into 'sibling' classes?
Incidentally, my initial IProvider implementations are created via an abstract factory, so maybe that might be another area I should focus this IData dependency on(?)
You should still use constructor injection because dependencies should hardly ever be optional.
You are trying to prevent constructor over-injection in the IProviderFactory implementation, and you probably don't want to inject the container into your factory to prevent falling into the Service Locator anti-pattern.
If however you define your IProviderFactory implementation INSIDE your Composition Root, you prevent yourself from doing Service Locator, even though you inject the container, since Service Locator is not about mechanics.
So you should define your ProviderFactory implementation as close to your Unity configuration as possible and it should look something like this:
public class ProviderFactory : IProviderFactory
{
private readonly Dictionary<string, Type> providerTypes;
private readonly Container container;
public ProviderFactory(Dictionary<string, Type> providerTypes,
Container container) {
this.providerTypes = providerTypes;
this.container = container;
}
public IProvider CreateProvider(string name) {
return (IProvider)this.container.Resolve(this.providerTypes[name]);
}
}
This implementation can be registered as singleton in Unity. This saves you from having to do constructor over-injection into your factory, while staying away from Service Locator.

Simple Injector - inject container property

I want to inject Container property via SimpleInjector. I didn't find any functionality of SimpleInjector for that.
Then I wanted to register self container to itself, but Container has no interface.
I want this functionality because I don't to transfer Container object via constructor - because why if I can use auto inject of register objects.
My usage idea:
var container = new Container();
container.Options.AutowirePropertiesWithAttribute<InjectableProperty>();
container.Register<ISomething, Something>(Lifestyle.Singleton);
ISomething:
public interface ISomething
{
void SomeMethod();
}
Something class:
public class Something : ISomething
{
public void SomeMethod()
{
var environment = _container.GetInstance<IEnvironment>();
environment.DoSomething();
}
[InjectableProperty] // - maybe it is not possible (I don't know it)
Container Container {get;set;}
}
Do you have any idea to achieve that?
Thank you very much.
Prevent having your application code depend upon the container. The only place in your application that should know about the existence of your DI library is the Composition Root (the place where you register all your dependencies).
Instead of letting each class call back into the container (which is called the Service Locator anti-pattern), prefer using Dependency Injection. With Dependency Injection you inject dependencies instead of asking for them.
So you can rewrite your class to the following:
public class Something : ISomething
{
private readonly IEnvironment environment;
public Something (IEnvironment environment)
{
this.environment = environment;
}
public void SomeMethod()
{
this.environment.DoSomething();
}
}
Also, prevent doing any logic in your constructors besides storing the incoming dependencies. This allows you to compose object graphs with confidence.
In some cases however, it can still be useful to inject the Container into another class. For instance when creating a factory class that is located inside the Composition Root. In that case you can still use constructor injection, like this:
// Defined in an application layer
public interface IMyFactory
{
IMyService CreateService();
}
// Defined inside the Composition Root
public class MyFactory : IMyFactory
{
private readonly Container container;
public MyFactory(Containter container)
{
this.container = container;
}
public IMyService CreateService(ServiceType type)
{
return type == ServiceType.A
? this.container.GetInstance<MyServiceA>()
: this.container.GetInstance<MyServiceB>();
}
}
If Simple Injector detects a Container constructor argument, it will inject itself into the constructor automatically.

Ways to setup a Ninject singleton

I have a class (MyFacade) that I injected parameter(s) with Ninject:
class MyFacade
{
IDemoInterface demo;
public MyFacade(IDemoInterface demo)
{
this.demo = demo;
}
public void MyMethod()
{
Console.WriteLine(demo.GetInfo());
}
}
Of course, I have to setup the Ninject to inject the appropiate implementation of my parameter (IDemoInterface)
I know, I can instantiate MyFacade object by doing kernel.Get<MyFacade>(); without setting anything else. Currently my facade doesn't have an interface (because it is my only implementation, maybe I will add its interface for standard proposes)
if I want to make this facade singlenton, I know two ways: create a empty constructor and pass a parameter by doing this kernel.Get<IDemoInterface>(); or by setup Ninject like: kernel.Bind<MyFacade>().To<MyFacade>().InSingletonScope();
The second one look a better approach, but do you know any other way to setup it in a singleton way?
When setting up your bindings, you need to bind your dependencies. It is always better to setup your dependencies in your bindings, as opposed to doing a kernel.Get<T>() in a constructor. You are using IOC, so leverage the framework you are using to do the injection for you.
In your second example binding, what you are missing is binding in your IDemoInterface. Your bindings should look like this:
//bind the dependency to the implementation.
kernel.Bind<IDemoInterface>().To<DemoInterface>();
//since you bound your dependency, ninject should now have
// all the dependencies required to instantiate your `MyFacade` object.
kernel.Bind<MyFacade>().To<MyFacade>().InSingletonScope();
If you do not want the container to manage the lifecycle of your singleton by using InSingletonScope(), but still wants it to get injected, I can think of 2 ways to go about it. Choose which one suits better to your needs. Consider the following ISingleton (name your interface) implementation:
public class ConcreteSingleton : ISingleton
{
private static readonly Lazy<ConcreteSingleton> _instance = new Lazy<ConcreteSingleton>(() => new ConcreteSingleton());
private ConcreteSingleton() { }
public static ConcreteSingleton Instance
{
get
{
return _instance.Value;
}
}
}
Alter the singleton class to have a GetInstance(...) method
In this method (my preferred approach), you won't be calling kernel.Inject(instance) each time, only for the first time the singleton is initialized. Adding the following method to your ConcreteSingleton class:
public static ConcreteSingleton GetInstance(IKernel kernelForInjection)
{
if (_instance.IsValueCreated == false)
{
kernelForInjection.Inject(_instance.Value);
}
return _instance.Value;
}
And using this binding:
kernel.Bind<ISingleton>().ToMethod(c => ConcreteSingleton.GetInstance(c.Kernel));
Will achieve the desired behavior of not having a public constructor but enabling your facade to be efficiently injected.
Perform injection each time the ISingleton instance is requested
If by any reason you are not allowed to modify your ConcreteSingleton: This approach will wrap the singleton creation in a provider to efficiently inject the instance only for the first time it is created. It is important to note that the provider itself must be registered as a singleton.
internal class ConcreteSingletonProvider : Provider<ISingleton>
{
public IKernel Kernel { get; set; }
//Just a wrapper
private readonly Lazy<ISingleton> _lazy = new Lazy<ISingleton>(() => ConcreteSingleton.Instance);
public ConcreteSingletonProvider(IKernel kernel)
{
Kernel = kernel;
}
protected override ISingleton CreateInstance(IContext context)
{
if (_lazy.IsValueCreated == false)
{
Kernel.Inject(ConcreteSingleton.Instance);
}
return _lazy.Value;
}
}
And your bindings should be like this:
kernel.Bind<ISingleton>().ToProvider<ConcreteSingletonProvider>();
kernel.Bind<ConcreteSingletonProvider>().ToSelf().InSingletonScope();
This gist has a complete working sample for the above approach.
Hope that helps!

Categories

Resources