Override default constructor for auto-factory

25 views
Skip to first unread message

Tomas C

unread,
Jul 15, 2020, 3:57:19 PM7/15/20
to structuremap-users
I am trying to use auto-factory as in the following example. I am trying to have the auto-factory call a specific constructor which is NOT the default chosen by StructureMap. I cannot seem to get it to work using only configuration methods. It only works if I mark the desired constructor with the [DefaultConstructor] attribute.

class Program
{
	static void Main(string[] args)
	{
		try
		{
			var container = new Container(new Registry());
 
			IWidgetFactory widgetFactory = container.GetInstance<IWidgetFactory>();
 
			var widget = widgetFactory.Create("test");
		}
		catch (Exception exception)
		{
			Debug.WriteLine(exception);
		}
	}
 }
 
public class Registry: StructureMap.Registry
{
	public Registry()
	{
		For<IWidget>().Use<Widget>();
			//.SelectConstructor(() => new Widget("_"));
			//.Ctor<string>("@string");
		// ForConcreteType<Widget>().Configure.SelectConstructor(() =>new Widget("_"));
 
		For<IWidgetFactory>().CreateFactory();
	}
}
 
public class WidgetIWidget
{
	public Widget()
		=> Debug.WriteLine($"Creating {nameof(Widget)}");
 
	//[DefaultConstructor]
	public Widget(string @string)
		=> Debug.WriteLine($"Creating {nameof(Widget)}: string {@string}");
 
	public Widget(int @int)
		=> Debug.WriteLine($"Creating {nameof(Widget)}: int {@int}");
 
	public Widget(int @int, string @string)
		=> Debug.WriteLine($"Creating {nameof(Widget)}{@int} {@string}");
 
	public Widget(string string1, string string2)
		=> Debug.WriteLine($"Creating {nameof(Widget)}{string1} {string2}");
}
 
public interface IWidget
{}
 
public interface IWidgetFactory
{
	IWidget Create(string string1);
}
Reply all
Reply to author
Forward
0 new messages