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.
Related
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>();
I am looking for some help with a simple "Hello World" example of DI. What I don't understand is how to initialize the classes "Foo" and "Bar" within a DI framework (autofac).
namespace AutofacTesting
{
//these classes are intended to be used with autofac / DI
public interface IFooBar
{
void Draw();
}
public class Bar : IFooBar
{
public void Draw()
{
MessageBox.Show("Drawing something in Bar");
}
}
public class Foo : IFooBar
{
public void Draw()
{
MessageBox.Show("Drawing somthing in Foo");
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var builder = new ContainerBuilder();
builder.RegisterType<Bar>().As<IFooBar>();
builder.RegisterType<Foo>().As<IFooBar>();
var container = builder.Build();
var taskController = container.Resolve<IFooBar>();
taskController.Draw();
int a = 1;
}
}
}
I think you mean you want to resolve a Bar or Foo class as the concrete implementation, not instantiate it. If so you could write:
var builder = new ContainerBuilder();
builder.RegisterType<Bar>().Named<IFooBar>("Bar");
builder.RegisterType<Foo>().Named<IFooBar>("Foo");
var container = builder.Build();
var taskController = container.ResolveNamed<IFooBar>("Bar");
taskController.Draw();
I also realize this is a hello world application, but be careful not to fail into the anti-pattern of using a service locator (i.e. using contain.Resolve all over the place). Instead, consider designs which will allow you to have all the registration and resolving happen in the same place, named a composition root.
I mention this caution becuase having this level of ambiguity (i.e. multiple concreate types being registered for a given interface) can cause one to start using the service locator pattern. Instead, in more complex applications, consider refactoring your API to have less ambiguity upon resolving registered types.
I need some help in auto-registering generics using StructureMap. Here is my scenario:
public class Object<T>
{
}
public interface IBehvior<T>
{
void DoSomething(T t);
}
public class Behvior<T> : IBehvior<Object<T>>
{
public void DoSomething(Object<T> t)
{
}
}
What I want to accomplish is something like:
var x = ObjectFactory.GetInstance<IBehavior<Object<int>>();
But when I run this statement, it gives me an error that no default instance is configured. In my StructureMap configuration I've used
ConnectImplementationsToTypesClosing(typeof(IBehavior<>))
But it still doesn't work!
Note that this worked fine if I didn't have Object. For example, if I have:
public class IntBehavior : IBehavior<int>
{
}
Everything works perfectly fine. But when I replace int with a generic type, it doesn't work!
Any ideas?
Ok I discovered the solution here:
http://lostechies.com/jimmybogard/2010/01/07/advanced-structuremap-custom-registration-conventions-for-partially-closed-types/
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.
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).