Structure map - Conditionally select a concrete type for an interface based on the type of the instance to which the dependency is injected

StackOverflow https://stackoverflow.com/questions/20796441

Pergunta

I have two wcf rest services as follows

using StructureMap;

namespace x.services
{
    public class Global : System.Web.HttpApplication
    {
        ObjectFactory.Configure(x =>
            {
                /* How do I configure Structure map to Use 
                   x.services.service1.Validator for constructing 
                   x.services.service1.Service1 Instances and
                   x.services.service2.Validator for constructing 
                   x.services.service2.Service2 Instances ** */
            }
    }
    public interface IValidator
    {
        /*...*/
    }
}
namespace x.services.service1
{
    public class Service1 : IService1
    {
        public Service1(IValidator validator)
        {
            /*...*/
        }
    }
    public class Validator : IValidator
    {
        /*...*/
    }
}
namespace x.services.service2
{
    public class Service2 : IService2
    {
        public Service2(IValidator validator)
        {
            /*....*/
        }
    }
    public class Validator : IValidator
    {
        /*...*/
    }
}

The question goes here too

How do I configure Structure map to Use x.services.service1.Validator for constructing x.services.service1.Service1 Instances and x.services.service2.Validator for constructing x.services.service2.Service2 Instances

Foi útil?

Solução

We can use explicit mapping:

// As precise IService1 mapping as possible
x.For<IService1>() 
   .Use<x.services.service1.Service1>()
    .Ctor<IValidator>("validator")
     .Is<x.services.service1.Validator>();

// IService2 
x.For<IService2>() 
   .Use<x.services.service2.Service2>()
    .Ctor<IValidator>("validator")
     .Is<x.services.service2.Validator>();

EDIT: to make some type singleton

x.For<x.services.service2.Validator>()
  .Singleton()
  .Use<x.services.service2.Validator>();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top