Structure map: class class at runtime

I have an interface and class defined below

public interface IShape { } public class Square : IShape { } 

I know that I can configure this to inject dependencies in the Structure Map, as shown below.

 ObjectFactory.Initialize(x => { x.For<IShape>().Use<Square>().Named("Square"); } ); 

However, I am wondering how to set up a configuration card if I only know the Concrete type at runtime. For example, I would like to do the following:

 ObjectFactory.Initialize(x => { x.For<IShape>().Use<Typeof(Square)>().Named("Square"); } ); 

EDIT: A new shape object (such as a circle) will be connected using an optional DLL. Consequently, design must also cope with this situation.

Any advice would be highly appreciated.

thanks

+4
source share
2 answers

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); } ); 
+1
source

Some lambda expressions may 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(); } } 
0
source

All Articles