Castle Windsor

让我们从Web API的集成点开始,它们是IDependencyResolverIDependencyScope接口。IDependencyResolver和其他接口的名称可能与MVC中的接口相同,但不要混淆,因为它们位于不同的名称空间中,并且与MVC中使用的接口不同。

1 IDependencyResolver

那么这个IDependencyResolver是什么?基本上它表示依赖注入容器,用于解析请求范围之外的所有内容。为了简化,它只是意味着使用此解析WebApi的所有接口。那么它在代码中看起来如何。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dependencies;
using Castle.MicroKernel;
 
internal class DependencyResolver : System.Web.Http.Dependencies.IDependencyResolver
{
    private readonly IKernel kernel;
 
    public DependencyResolver(IKernel kernel)
    {
        this.kernel = kernel;
    }
 
    public IDependencyScope BeginScope()
    {
        return new DependencyScope(kernel);
    }
 
    public object GetService(Type type)
    {
        return kernel.HasComponent(type) ? kernel.Resolve(type) : null;
    }
 
    public IEnumerable<object> GetServices(Type type)
    {
        return kernel.ResolveAll(type).Cast<object>();
    }
 
    public void Dispose()
    {
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dependencies;
using Castle.MicroKernel;
using Castle.MicroKernel.Lifestyle;
 
public class DependencyScope : IDependencyScope
{
    private readonly IKernel kernel;
 
    private readonly IDisposable disposable;
 
    public DependencyScope(IKernel kernel)
    {
        this.kernel = kernel;
        disposable = kernel.BeginScope();
    }
 
    public object GetService(Type type)
    {
        return kernel.HasComponent(type) ? kernel.Resolve(type) : null;
    }
 
    public IEnumerable<object> GetServices(Type type)
    {
        return kernel.ResolveAll(type).Cast<object>();
    }
 
    public void Dispose()
    {
        disposable.Dispose();
    }
}

using System.Web.Http;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
 
public class WebApiInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Classes
                .FromThisAssembly()
                .BasedOn<ApiController>()
                .LifestyleScoped()
            );
    }
}

global

var container = new WindsorContainer();
container.Install(FromAssembly.This());
GlobalConfiguration.Configuration.DependencyResolver = new CastleWindsor.DependencyResolver(container.Kernel);

原文http://www.macaalay.com/2014/08/27/using-castle-windsor-with-web-api-apicontroller/

猜你喜欢

转载自www.cnblogs.com/chenyishi/p/9341592.html