webadvanced / Structuremap.MVC5

Apache License 2.0
21 stars 9 forks source link

Questions regarding scope and initialization #8

Open ThisNoName opened 9 years ago

ThisNoName commented 9 years ago

In previous version, I have to specify HttpContextScoped. I can still do it in 3.1 but if this is done in a Registry in a library, it has to reference StructureMap.Web, seems defeat the purpose of that separation. Is this no longer necessary because I read something about container per request?

For<IDatabase>().Use(() => new Database("DefaultDb"))
    .LifecycleIs<HttpContextLifecycle>();

Another thing, one of the mediator interface (MediatR) I use take input parameter.

 public class Mediator : IMediator    {
      public Mediator(ServiceLocatorProvider serviceLocatorProvider)   {
            _serviceLocatorProvider = serviceLocatorProvider;
       }

If I left everything default, when injected, it will complain no parameter-less constructor. Somehow through trial and error, I manage to get it work by changing the IoC initialize to the following. But I have no idea if it's the right way. Can someone help take a look?

    public static IContainer Initialize()
    {
        Container container = new Container(x => x.AddRegistry<DefaultRegistry>());

        container.Configure(cfg => cfg.For<ServiceLocatorProvider>()
            .Use(new ServiceLocatorProvider(() => new StructureMapDependencyScope(container))));

        return container;
    }
eddiegroves commented 9 years ago

Regarding HttpContextScoped, this has been effectively deprecated and StructureMap.Web is provided to make it easier to upgrade to SM3. As you say, HttpContextScopedis replaced with the use of nested containers. So just use For..Use with default Transient lifecyle.

And I guess better late than never, but MediatR has dropped CSL in favor of delegates:

cfg.For<SingleInstanceFactory>().Use<SingleInstanceFactory>(ctx => t => ctx.GetInstance(t));
cfg.For<MultiInstanceFactory>().Use<MultiInstanceFactory>(ctx => t => ctx.GetAllInstances(t));
cfg.For<IMediator>().Use<Mediator>();