Autofac注册特定的方法参数类型

时间:2014-04-11 07:40:34

标签: c# .net inversion-of-control ioc-container autofac

我正在使用Autofac IOC进行构造验证。我无法弄清楚如何在IOC中注册这些类,以便LogotypeService获得LogoImageValidatorAdServiceAdValidator注入其构造函数中。

我不想指定应该注入哪个SomeClass实例。

我有:

  • 一个验证界面(IImageValidator)
  • 公共验证逻辑的一个基类(ImageValidatorBase)
  • 两个包含特定valiation逻辑的子类(LogoImageValidator和AdImageValidator)
  • 一个服务接口(IService)
  • 两个服务,每个服务应使用不同的子类进行验证。 (LogotypeService应使用LogoImageValidator)和(AdService应使用AdValidator)

接口

public interface IImageValidator
{
    bool ValidFileSize();
}

基类:

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

子类LogoImageValidator

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

子类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    
    }
}

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

这似乎与此问题重叠:Inject Specific Type With Autofac

答案表明根据上下文使用不同的接口。