0

I'm very new to ASP.Core. We have a project and we must use Dependency Injection and StructureMap. I'm wondering if it is the right way to put the Container in the StartUp.cs file in the following method. And if it is safe to put the IHttpContextAccessor in the configuration like below:

    public void ConfigureServices(IServiceCollection services) {

        Container container = new Container(expr => {
            expr.For<IDataContextService>().Use<DataContextService>();
            expr.For<IHttpContextAccessor>().Use<HttpContextAccessor>();
            expr.For<ISessionService>().Use<SessionService>();
        });
        services.AddSingleton<IContainer>(container);
    }

1 Answer 1

2

when changing the base Dependency container in ASP.NET core, ConfigureServices needs to return an instance of IServiceProvider

Andew Lock in his blog post shows you how to perform that.

Taken from his blog post, it would be something like this for StructureMap

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc()
        .AddControllersAsServices();

    return ConfigureIoC(services);
}

public IServiceProvider ConfigureIoC(IServiceCollection services)
    {
        var container = new Container();

        container.Configure(config =>
        {
            // Register stuff in container, using the StructureMap APIs...
            config.Scan(_ =>
            {
                _.AssemblyContainingType(typeof(Startup));
                _.WithDefaultConventions();
                _.AddAllTypesOf<IGamingService>();
                _.ConnectImplementationsToTypesClosing(typeof(IValidator<>));
            });

            config.For(typeof(IValidator<>)).Add(typeof(DefaultValidator<>));
            config.For(typeof(ILeaderboard<>)).Use(typeof(Leaderboard<>));
            config.For<IUnitOfWork>().Use(_ => new UnitOfWork(3)).ContainerScoped();

            //Populate the container using the service collection
            config.Populate(services);
        });

        return container.GetInstance<IServiceProvider>();

    }
}

If ever you're interested in using Autofac you can refer to ASP.NET documentation on that subject

Sign up to request clarification or add additional context in comments.

Comments

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.