Is it possible to inject parameters into protected constructors using Unity? - dependency-injection

I can do this in Castle Windsor:
public abstract class AbstractFactory
{
protected AbstractFactory(Foo constructorParm)
{
// Do something with parameter...
}
}
public class DescendentFactory : AbstractFactory
{
public DescendentFactory(Foo constructorParm) : base(constructorParm)
{
}
}
// The container is configured via XML, the service AbstractFactory and the
// type DescendentFactory
container.Resolve<AbstractFactory>("DescendentFactoryId", new { constructorParm = injectedValue });
Is this possible in Unity? I've tried doing it but it complains that it can't find the constructor. It seems I can only inject via the sub-type.

You can only inject via the sub-type. It needs a public constructor.

Related

SimpleInjector - Register a type for all it's interfaces

Is it possible to register a type for all it's implementing interfaces? E.g, I have a:
public class Bow : IWeapon
{
#region IWeapon Members
public string Attack()
{
return "Shooted with a bow";
}
#endregion
}
public class HumanFighter
{
private readonly IWeapon weapon = null;
public HumanFighter(IWeapon weapon)
{
this.weapon = weapon;
}
public string Fight()
{
return this.weapon.Attack();
}
}
[Test]
public void Test2b()
{
Container container = new Container();
container.RegisterSingle<Bow>();
container.RegisterSingle<HumanFighter>();
// this would match the IWeapon to the Bow, as it
// is implemented by Bow
var humanFighter1 = container.GetInstance<HumanFighter>();
string s = humanFighter1.Fight();
}
It completely depends on your needs, but typically you need to use the Container's non-generic registration method. You can define your own LINQ queries to query the application's metadata to get the proper types, and register them using the non-generic registration methods. Here's an example:
var weaponsAssembly = typeof(Bow).Assembly;
var registrations =
from type in weaponsAssembly.GetExportedTypes()
where type.Namespace.Contains(".Weapons")
from service in type.GetInterfaces()
select new { Service = service, Implementation = type };
foreach (var reg in registrations)
{
container.Register(reg.Service, reg.Implementation);
}
If you need to batch-register a set of implementations, based on a shared generic interface, you can use the RegisterManyForOpenGeneric extension method:
// include the SimpleInjector.Extensions namespace.
container.RegisterManyForOpenGeneric(typeof(IValidator<>),
typeof(IValidator<>).Assembly);
This will look for all (non-generic) public types in the supplied assembly that implement IValidator<T> and registers each of them by their closed-generic implementation. If an type implements multiple closed-generic versions of IValidator<T>, all versions will be registered. Take a look at the following example:
interface IValidator<T> { }
class MultiVal1 : IValidator<Customer>, IValidator<Order> { }
class MultiVal2 : IValidator<User>, IValidator<Employee> { }
container.RegisterManyForOpenGeneric(typeof(IValidator<>),
typeof(IValidator<>).Assembly);
Assuming the given interface and class definitions, the shown RegisterManyForOpenGeneric registration is equivalent to the following manual registration:
container.Register<IValidator<Customer>, MultiVal1>();
container.Register<IValidator<Order>, MultiVal1>();
container.Register<IValidator<User>, MultiVal2>();
container.Register<IValidator<Employee>, MultiVal2>();
It would also be easy to add convenient extension methods. Take for instance the following extension method that allows you to register a single implementation by all its implemented interfaces:
public static void RegisterAsImplementedInterfaces<TImpl>(
this Container container)
{
foreach (var service in typeof(TImpl).GetInterfaces())
{
container.Register(service, typeof(TImpl));
}
}
It can be used as follows:
container.RegisterAsImplementedInterfaces<Sword>();

structuremap inject a dictionary list of interfaces

Say I have a list of protocol handlers, and the client service knows which protocol to use based on an enum value, it would be nice to selected the protocol from the list of i/fs passed in.
How can I achieve this in StructureMap?:
public EmailTransportService(interfaces...,
IDictionary<EmailAccountType, IEmailTransportHandler> transportHandlers)
At the moment, I'm using ObjectFactory with get named instance like so:
_emailTransportHandlers = new Dictionary<EmailAccountType, string>
{
{EmailAccountType.Pop3, "Pop3Handler"},
{EmailAccountType.IMAP, "IMapHandler"}
};
then resolving like so:
private IEmailTransportHandler GetTransportHandler(EmailAccountType accountType)
{
return ObjectFactory.GetNamedInstance<IEmailTransportHandler>(_emailTransportHandlers[accountType]);
}
but I don't like this as its difficult within my unit tests to verify the calls to the handlers.
My service registry looks like so:
public EmailTransportServiceRegistry()
{
Scan(x =>
{
....
});
For<IEmailTransportHandler>().Use<ActiveUpPop3Handler>().Named("Pop3Handler");
For<IEmailTransportHandler>().Use<ActiveUpIMap4Handler>().Named("IMapHandler");
}
So basically I'm relying on named instances based on the dictionary list of protocol types.
My solution was to have a static register method from the client service like so:
public static IDictionary<EmailAccountType, IEmailTransportHandler> RxHandlerRegistration()
{
return new Dictionary<EmailAccountType, IEmailTransportHandler>
{
// following registrations use ActiveUp library for pop3/imap (http://mailsystem.codeplex.com/)
{EmailAccountType.Pop3, ObjectFactory.GetInstance<ActiveUpPop3Handler>()},
{EmailAccountType.IMAP, ObjectFactory.GetInstance<ActiveUpIMap4Handler>()}
};
}
Then in the ServiceRegistry class:
public class EmailTransportServiceRegistry : ServiceRegistry
{
public EmailTransportServiceRegistry()
{
// other registries...
For<IDictionary<EmailAccountType, IEmailTransportHandler>>().Use(x => EmailTransportService.RxHandlerRegistration());
}
}

How do I handle classes with static methods with Ninject?

How do I handle classes with static methods with Ninject?
That is, in C# one can not have static methods in an interface, and Ninject works on the basis of using interfaces?
My use case is a class that I would like it to have a static method to create an
unpopulated instance of itself.
EDIT 1
Just to add an example in the TopologyImp class, in the GetRootNodes() method, how would I create some iNode classes to return? Would I construct these with normal code practice or would I somehow use Ninject? But if I use the container to create then haven't I given this library knowledge of the IOC then?
public interface ITopology
{
List<INode> GetRootNodes();
}
public class TopologyImp : ITopology
{
public List<INode> GetRootNodes()
{
List<INode> result = new List<INode>();
// Need code here to create some instances, but how to without knowledge of the container?
// e.g. want to create a few INode instances and add them to the list and then return the list
}
}
public interface INode
{
// Parameters
long Id { get; set; }
string Name { get; set; }
}
class NodeImp : INode
{
public long Id
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public string Name
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
}
// Just background to highlight the fact I'm using Ninject fine to inject ITopology
public partial class Form1 : Form
{
private ITopology _top;
public Form1()
{
IKernel kernal = new StandardKernel(new TopologyModule());
_top = kernal.Get<ITopology>();
InitializeComponent();
}
}
If you're building a singleton or something of that nature and trying to inject dependencies, typically you instead write your code as a normal class, without trying to put in lots of (probably incorrect) code managing the singleton and instead register the object InSingletonScope (v2 - you didnt mention your Ninject version). Each time you do that, you have one less class that doesnt surface its dependencies.
If you're feeling especially bloody-minded and are certain that you want to go against that general flow, the main tools Ninject gives you is Kernel.Inject, which one can use after you (or someone else) has newd up an instance to inject the dependencies. But then to locate one's Kernelm you're typically going to be using a Service Locator, which is likely to cause as much of a mess as it is likely to solve.
EDIT: Thanks for following up - I see what you're after. Here's a hacky way to approximate the autofac automatic factory mechanism :-
/// <summary>
/// Ugly example of a not-very-automatic factory in Ninject
/// </summary>
class AutomaticFactoriesInNinject
{
class Node
{
}
class NodeFactory
{
public NodeFactory( Func<Node> createNode )
{
_createNode = createNode;
}
Func<Node> _createNode;
public Node GenerateTree()
{
return _createNode();
}
}
internal class Module : NinjectModule
{
public override void Load()
{
Bind<Func<Node>>().ToMethod( context => () => Kernel.Get<Node>() );
}
}
[Fact]
public void CanGenerate()
{
var kernel = new StandardKernel( new Module() );
var result = kernel.Get<NodeFactory>().GenerateTree();
Assert.IsType<Node>( result );
}
}
The ToMethod stuff is a specific application of the ToProvider pattern -- here's how you'd do the same thing via that route:-
...
class NodeProvider : IProvider
{
public Type Type
{
get { return typeof(Node); }
}
public object Create( IContext context )
{
return context.Kernel.Get<Node>();
}
}
internal class Module : NinjectModule
{
public override void Load()
{
Bind<Func<Node>>().ToProvider<NodeProvider>();
}
}
...
I have not thought this through though and am not recommending this as A Good Idea - there may be far better ways of structuring something like this. #Mark Seemann? :P
I believe Unity and MEF also support things in this direction (keywords: automatic factory, Func)
EDIT 2: Shorter syntax if you're willing to use container-specific attributes and drop to property injection (even if Ninject allows you to override the specific attributes, I much prefer constructor injection):
class NodeFactory
{
[Inject]
public Func<Node> NodeFactory { private get; set; }
public Node GenerateTree()
{
return NodeFactory();
}
}
EDIT 3: You also need to be aware of this Ninject Module by #Remo Gloor which is slated to be in the 2.4 release
EDIT 4: Also overlapping, but not directly relevant is the fact that in Ninject, you can request an IKernel in your ctor/properties and have that injected (but that doesn't work directly in a static method).

Problems integrating nServiceBus with StructureMap

I'm trying to use StructureMap with nServiceBus.
The Project:
Uses a GenericHost Endpoint to send command messages
Configures nServiceBus using the StructMapBuilder.
Uses a simple StructureMap registry config
Uses a start up class TestServer supporting IWantToRunAtStartup
The TestServer class has ctor dependency on a TestManager class
The TestManager class has ctor dependency on IBus
ObjectFactory.WhatDoIHave() shows StructureMap knows how to construct the classes.
When run I get buildup errors. nServiceBus seems to be overwriting the config?
Note that when I add a IBus ctor depenendency to my event handlers without any other config all appears fine.
Error:
Exception when starting endpoint, error has been logged. Reason: Error creating object with name 'nSeviceBusStructureMapTest.TestServer' : Unsatisfied dependency expressed through constructor argument with index 0 of type [nSeviceBusStructureMapTest.ITestManager] : No unique object of type [nSeviceBusStructureMapTest.ITestManager] is defined : Unsatisfied dependency of type [nSeviceBusStructureMapTest.ITestManager]: expected at least 1 matching object to wire the [miningServiceManage] parameter on the constructor of object [nSeviceBusStructureMapTest.TestServer]
Source:
using System;
using System.Diagnostics;
using NServiceBus;
using StructureMap;
using StructureMap.Configuration.DSL;
namespace nSeviceBusStructureMapTest
{
public class TestSmRegistry : Registry
{
public TestSmRegistry()
{
For<ITestManager>().Use<TestManager>();
For<TestServer>().Use<TestServer>();
}
}
public class TestEndPoint : AsA_Server, IConfigureThisEndpoint
{
public void Init()
{
Configure.With().StructureMapBuilder(ObjectFactory.Container);
ObjectFactory.Configure(c => c.AddRegistry<TestSmRegistry>());
Debug.WriteLine(ObjectFactory.WhatDoIHave());
}
}
public class TestServer : IWantToRunAtStartup
{
public TestServer(ITestManager miningServiceManage)
{
_miningServiceManage = miningServiceManage;
}
private readonly ITestManager _miningServiceManage;
public void Run()
{
_miningServiceManage.Run();
}
public void Stop() { }
}
public interface ITestManager
{
void Run();
}
public class TestManager : ITestManager
{
public TestManager(IBus bus)
{
_bus = bus;
}
private readonly IBus _bus;
public void Run()
{
if (_bus == null) Debug.WriteLine("Error no bus");
// Send messages on bus;
}
}
}
<MsmqTransportConfig InputQueue="test" ErrorQueue="error" NumberOfWorkerThreads="1" MaxRetries="5" />
<UnicastBusConfig>
<MessageEndpointMappings>
</MessageEndpointMappings>
</UnicastBusConfig>
Any ideas?
You have to specify IWantCustomInitialization on the endpoint config class. Otherwise NServiceBus won't call the Init() method. You also need to specify what serializer to use so add:
Configure.With()
.StructureMapBuilder()
.XmlSerializer();
Hope this helps!

interface<T> binding in Castle Windsor

I have a common datacontainer
interface IDataContainer
I use it for different types of T
IPerson, ISuperMan etc
In castle i regsiter it with
container.AddComponentWithLifestyle<IDataContainer<IPerson>, DataContainer<Person>>(LifestyleType.Transient);
container.AddComponentWithLifestyle<IDataContainer<ISuperMan>, DataContainer<SuperMan>>(LifestyleType.Transient);
at runtime castle creates the dependency with eg.
IDataContainer<IPerson> test = container.GetService<IDataContainer<IPerson>>();
but it fails with an unable to cast...the classes implements the interface and namespaces are correct etc.
The call
IPerson test = container.GetService<IPerson>();
Works (with the registration of <IPerson,Person>)
Cant castle resolve an interface<T> or ?
So this is way late, but I think I know what you're trying to do here. I'm able to get this to pass:
IDataContainer<IPerson> test = container.GetService<IDataContainer<IPerson>>();
By registering components like this:
public class IoC
{
public static void SetUp()
{
container = new WindsorContainer();
container.AddComponent<IPerson, Person>();
//container.AddComponentWithLifestyle<IDataContainer<IPerson>, DataContainer<Person>>(LifestyleType.Transient);
//container.AddComponentWithLifestyle<IDataContainer<ISuperMan>, DataContainer<SuperMan>>(LifestyleType.Transient);
container.AddComponentWithLifestyle("DataContainers", typeof(IDataContainer<>), typeof(DataContainer<>), LifestyleType.Transient);
}
public void TestOne()
{
SetUp();
var test = container.GetService<IDataContainer<IPerson>>();
Assert.That(test, Is.Not.Null);
}
public void TestTwo()
{
SetUp();
var test = container.GetService<IPerson>();
Assert.That(test, Is.Not.Null);
}
}
internal interface IDataContainer<T> { }
internal class DataContainer<T> : IDataContainer<T> { }
internal interface IPerson { }
class Person : IPerson { }
internal interface ISuperMan { }
class SuperMan : ISuperMan { }
The two lines that are commented out are the two lines that exist in the question.
This has nothing to do with Windsor. You get a casting error because C# 2.0 and 3.0 do not support generics covariance. You're probably making DataContainer<T> implement IDataContainer<T>, which means that DataContainer<Person> implements IDataContainer<Person> and not IDataContainer<IPerson> which is what you're requesting from the container.

Resources