Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up structure map in a c# console application

I'm getting this error:

StructureMap Exception Code:  202
No Default Instance defined for PluginFamily 

My setup looks like:

Console.WriteLine("Structure Map");
SetupSM sm = new SetupSM();
sm.Setup();

ISomeThing someThing = ObjectFactory.GetInstance<ISomeThing>();
Console.WriteLine("something.HowManyTHings: " + someThing.HowManyThings("asdf"));



 public class SetupSM
    {
        public void Setup()
        {
            var c1 = new Container(config =>
            {
                config.Scan(scan =>
                {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
                });
            });

            var c2 = new Container(x =>
                                              {
                                                  x.For<ISomeThing>().Use<SomeThingOne>();
                                              });


        }
    }

This is my first try at using structure map, what am I missing? It seems the guide on their main website is very old using the old syntax etc.

like image 760
codecompleting Avatar asked Dec 22 '25 22:12

codecompleting


2 Answers

Try applying your configuration to the static ObjectFactory instead of seperate containers which you appear to throw away immediately..

public class SetupSM
    {
        public void Setup()
        {
            ObjectFactory.Configure(config =>
            { 
                config.Scan(scan =>
                {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
                });

                config.For<ISomething>().Use<SomeThingOne>();
            });
    }
like image 147
MattDavey Avatar answered Dec 24 '25 10:12

MattDavey


The previous answers are for StructureMap 2 or 3, but in StructureMap 4 the syntax has changed. You can see a complete solution here:

http://ardalis.com/using-structuremap-4-in-a-console-app

Essentially, ObjectFactory has been replaced with a Container instance. You can also optionally perform the configuration in a separate Registry instance, which is recommended. Thus your initialization code in Main() becomes:

static void Main(string[] args)
{
    var container = Container.For<ConsoleRegistry>();

    var app = container.GetInstance<Application>();
    app.Run();
    Console.ReadLine();
}

This keeps Main very clean, and allows Application to request any dependencies it needs through dependency injection and to follow the Explicit Dependencies Principle. Combined, these allow your application to be very composable and testable.

like image 45
ssmith Avatar answered Dec 24 '25 11:12

ssmith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!