Structure Map : concrete class at run time
I have an interface and a class defined as below
public interface IShape
{
}
public class Square : IShape
{
}
I know I can configure this for dependency injection in Structure Map as below.
ObjectFactory.Initialize(x =>
{
x.For<IShape>().Use<Square>().Named("Square");
}
);
However, I am wondering how I could configure the structure map if I can only know the Concrete Type during runtime. For example, I 开发者_JS百科would like to do as below.;
ObjectFactory.Initialize(x =>
{
x.For<IShape>().Use<Typeof(Square)>().Named("Square");
}
);
EDIT: A new shape object (i.e. circle) would be plugged in using an additional DLL. Hence the design should be able handle this situation as well.
Any advice would be much appreciated.
Thanks
This works for me.
public class ShapeHolder
{
public IShape shape{ get; set ;}
public string shapeName { get; set; }
}
//Run time shape creation
ShapeHolder shapeholder = factory.CreateShape();
ObjectFactory.Initialize(x =>
{
x.For(typeof(IShape)).Use(shapeholder.shape).Named(shapeholder.shapeName);
} );
Some lambda expressions might help you..
// Return a shape based on some runtime criteria
x.For<IShape>.Use(() => shapeFactory.Create());
public class ShapeFactory
{
public IShape Create()
{
// Return a shape based some criteria
return new Square();
}
}
精彩评论