在config.ipendendendencyResolver上获取施法错误= new UnityResolver(Co



我试图通过Unity容器在我的Web API项目中使用依赖项注入,但是我得到了编译时间异常

"不能隐式将'apiIntegrationApp.unityResolver'转换为'system.web.http.dependencies.idependencyResolver'。存在明确的转换(您是否缺少演员?("

我指的是我实施的链接

https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/depperency-indoction

var container = new UnityContainer();
container.RegisterType<IMFOCustomerRepository, MFOCustomerRepository>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);

这是我的IdependencyResolver接口和UnityResolver类定义

public interface IDependencyResolver : IDependencyScope, IDisposable
{
    IDependencyScope BeginScope();
}
public interface IDependencyScope : IDisposable
{
    object GetService(Type serviceType);
    IEnumerable<object> GetServices(Type serviceType);
}
 public class UnityResolver : IDependencyResolver
{
    protected IUnityContainer container;
    public UnityResolver(IUnityContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }
        this.container = container;
    }
    public object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }
    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return container.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return new List<object>();
        }
    }
    public IDependencyScope BeginScope()
    {
        var child = container.CreateChildContainer();
        return new UnityResolver(child);
    }
    public void Dispose()
    {
        Dispose(true);
    }
    protected virtual void Dispose(bool disposing)
    {
        container.Dispose();
    }
}

通常会出现此错误,因为类型不匹配(想想int myInt = 'some string'(或特定类并不能从预期的接口中继承。以下示例显示了以下示例:

public interface IClassA
{
    void DoSomething();
}
public class ClassA
{
    public void DoSomething()
    {
        // do something here
    }
}
public class Program
{
    static void Main(string[] args)
    {
        IClassA obj = new ClassA(); // throws error because ClassA doesn't inherit from IClassA
    }
}

解决此问题的解决方案将仅继承所需的接口,这是依赖注入的常见。

最新更新