首页 > 解决方案 > 使用 .net web api 和 tinyioc 解决依赖关系

问题描述

我让 TinyIoc 在 .net web api 中愉快地运行。我只是尝试添加一个使用 System.Web.Http.HttpClient 的服务类。我在容器中显式注册了我的新类,但是突然之间,我在应用程序启动时遇到了一堆运行时错误——tiny 找不到一堆 System.Web.Http 类。这是第一个这样的错误......

TinyIoC.TinyIoCResolutionException
HResult=0x80131500
Message=Unable to resolve type: System.Web.Http.Metadata.ModelMetadataProvider
Source=HubHacienda
StackTrace:
at TinyIoC.TinyIoCContainer.ResolveInternal(TypeRegistration registration, NamedParameterOverloads parameters, ResolveOptions options) in C:\Workspaces\HubHacienda_DEV\HubHacienda\TinyIoC.cs:line 3558
>   HubHacienda.dll!TinyIoC.TinyIoCContainer.ResolveInternal(TinyIoC.TinyIoCContainer.TypeRegistration registration, TinyIoC.NamedParameterOverloads parameters, TinyIoC.ResolveOptions options) Line 3557  C#
    HubHacienda.dll!TinyIoC.TinyIoCContainer.Resolve(System.Type resolveType) Line 1566 C#
    HubHacienda.dll!HubHacienda.TinyIoCDependencyResolver.GetService(System.Type serviceType) Line 36   C#
    [External Code] 
    HubHacienda.dll!HubHacienda.WebApiApplication.Application_Start() Line 1517:13 12/09/201817:13 12/09/201817:14 12/09/2018   C#
    [External Code] 

这里是 global.asax 中的 Application_Start() 方法

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

这是我的 WebApiConfig 类中的 Register() 方法...

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    //config.MapHttpAttributeRoutes();
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional },
        constraints: new { id = @"\d*" }
    );
    // sby
    // http://www.rbwestmoreland.com/posts/inversion-of-control-in-asp-net-web-api/
    var container = new TinyIoCContainer();
    // Repositorys
    container.Register<IJustifRepo, JustifRepo>();
    container.Register<IReferringAppsRepo, ReferringAppsRepo>();
    // then many more like this...

    config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

    config.DependencyResolver = new TinyIoCDependencyResolver(container);


}

最后,我的 TinyIocDependencyResolver 在这里...

public class TinyIoCDependencyResolver : IDependencyResolver
{
    private TinyIoCContainer _container;

    public TinyIoCDependencyResolver(TinyIoCContainer container)
    {
        if (container == null)
            throw new ArgumentNullException("container");

        _container = container;
    }

    public IDependencyScope BeginScope()
    {
        if (_disposed)
            throw new ObjectDisposedException("this", "This scope has already been disposed.");

        return new TinyIoCDependencyResolver(_container.GetChildContainer());
    }

    public object GetService(Type serviceType)
    {
        if (_disposed)
            throw new ObjectDisposedException("this", "This scope has already been disposed.");

        try
        {
            return _container.Resolve(serviceType);
        }
        catch (TinyIoCResolutionException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        if (_disposed)
            throw new ObjectDisposedException("this", "This scope has already been disposed.");

        try
        {
            return _container.ResolveAll(serviceType);
        }
        catch (TinyIoCResolutionException)
        {
            return Enumerable.Empty<object>();
        }
    }

    #region IDisposable

    bool _disposed;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_disposed)
            return;

        if (disposing)
            _container.Dispose();

        _disposed = true;
    }

    #endregion IDisposable
}

这对任何人都意味着什么?HttpClient,可能是导致我痛苦的添加,是显式实例化的,而不是通过 DI。为什么我应该得到不属于我的类的 DI 错误?所有项目的目标框架都是 .net 4.5。

标签: c#asp.net-web-apitinyioc

解决方案


推荐阅读