0

I have a StructureMap container already set up (in a separate project) like so:

    public class Container
    {
        public static StructureMap.Container Current { get; private set; }

        public static void InitIoC()
        {
            var container = new StructureMap.Container(
                c =>
                {
                    c.For<AppSettings>().Singleton();
                    c.For<ILogger>().Use<Logger>();
                    c.For<IReminderService>().Use<ReminderService>();
                    ...
                }
       }
    }

I would like this configuration to be used in .NET Core 2.0 Web API.

In my Startup.cs I have to do this to make it work:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.Add(ServiceDescriptor.Transient(typeof(ILogger), typeof(Logger)));
        ... // rewriting what is already configured
    }

How can I simply inject this same configuration into WebAPI?

1 Answer 1

2

You can try this:

 public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();                      
        //Create StructureMap container
        var container = new Container(); //This is Structuremap's container class, not your custom class
        container.Configure(config =>
        {
            //Add in your custom structuremap registry
            config.AddRegistry(new Container());
            //Push the .net Core Services Collection into StructureMap
            config.Populate(services);
        });
        //Register dependencies
        services.ConfigureDependencies();
        //Return the service provider
        return container.GetInstance<IServiceProvider>();
    }

I don't know if it's necessary but you can change your Container class be like:

public class Container: Registry
    {
        public Container()
        {               
           c.For<ILogger>().Use<Logger>();
           c.For<IReminderService>().Use<ReminderService>();
           //More mappings
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Yep. a little change here and there but it works. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.