0

I am using the Autofac IOC with construcor validation. I can't figure out how to register the classes in the IOC so that LogotypeService gets LogoImageValidator and AdService get AdValidator injected in it's constructors.

I don't want to specify which instance of SomeClass that should be injected.

I have:

  • One validation interface (IImageValidator)
  • One base class for the common validation logic (ImageValidatorBase)
  • Two subclasses which holds specific valiation logic (LogoImageValidator and AdImageValidator)
  • One service interface (IService)
  • Two services which each should use different subclasses for validation. (LogotypeService should use LogoImageValidator) and (AdService should use AdValidator)

Interface

public interface IImageValidator
{
    bool ValidFileSize();
}

Base class:

public abstract class ImageValidatorBase : IImageValidator
{    
    //constructor omitted
    Public abstract ValidFileSize()
    {
       //shared code
    }
}

Subclass LogoImageValidator

public class LogoImageValidator : ImageValidator
{
    //constructor omitted
    public override bool ValidFileSize()
    {
        //class specific code
    }
}

Subclass AdImageValidator

public class AdImageValidator : ImageValidator
{
    //constructor omitted
    public override bool ValidFileSize()
    {
        //class specific code
    }
}

IService

public interface IService{
    bool ValidFileSize();
}

LogotypeService

 public class LogotypeService : IService
 {
    private readonly ISomeClass _someClass;
    private readonly IImageValidator _imageValidator;

    public LogotypeService(ISomeClass someClass, IImageValidator imageValidator)
    {
        _someClass = someClass;
        _imageValidator = imageValidator;
    }

    public bool ValidFileSize()
    {
       _imageValidator.ValidFileSize();//use LogoImageValidator subclass here            
    }
}

AdService

 public class AdService : IService
 {
    private readonly ISomeClass _someClass;
    private readonly IImageValidator _imageValidator;

    public AdService(ISomeClass someClass, IImageValidator imageValidator)
    {
        _someClass = someClass;
        _imageValidator = imageValidator;
    }

    public bool ValidFileSize()
    {
       _imageValidator.ValidFileSize();//use AdValidator subclass here    
    }
}

Any ideas?

Steven
  • 166,672
  • 24
  • 332
  • 435
Tim Hansson
  • 309
  • 2
  • 16

1 Answers1

0

This appears to overlap with this question: Inject Specific Type With Autofac

The answer there suggests that different interfaces be used based on context.

Community
  • 1
  • 1
Travis Illig
  • 23,195
  • 2
  • 62
  • 85