21

我想使用 Castle Windsor 在 WebApi 应用程序中实现依赖注入。我有以下示例代码 -

界面 -

public interface IWatch
{
    {
        DateTime GetTime();
    }
}

以下Watch 类实现IWatch接口 -

public class Watch:IWatch
{
        public DateTime GetTime()
        {
            return DateTime.Now;
        }
}

WebApi 控制器 - WatchController如下 -

public class WatchController : ApiController
{
        private readonly IWatch _watch;

        public WatchController()
        {
            _watch = new Watch();
        }

        //http://localhost:48036/api/Watch
        public string Get()
        {
            var message = string.Format("The current time on the server is: {0}", _watch.GetTime());
            return message;
        }
}

目前我在 WatchController 构造函数中使用 Watch 启动 IWatch 对象。我想使用 Windsor Castle 依赖注入原理删除在构造函数中初始化 IWatch 的依赖。

任何人都可以为我提供在这种 WebApi 案例中实现依赖注入的步骤吗?提前致谢!

4

3 回答 3

71

CodeCaster、Noctis 和 Cristiano 感谢您的所有帮助和指导。我刚刚得到了上述查询的解决方案 -

第一步是使用 nuget在WebApi解决方案中安装Windsor.Castle包。

在此处输入图像描述

考虑以下代码片段 -

接口IWatch.cs

public interface IWatch
{
     DateTime GetTime();
}

Watch.cs

public class Watch:IWatch
{
    public DateTime GetTime()
    {
        return DateTime.Now;
    }
}

ApiController WatchController.cs定义如下: -

public class WatchController : ApiController
{
     private readonly IWatch _watch;

     public WatchController(IWatch watch)
     {
         _watch = watch;
     }

     public string Get()
     {
         var message = string.Format("The current time on the server is: {0}", _watch.GetTime());
         return message;
     }
}

在控制器中,我们通过 WatchController 构造函数中的 IWatch 对象注入了依赖项。我已经使用IDependencyResolverIDependencyScope来实现 web api 中的依赖注入。IDependencyResolver 接口用于解析请求范围之外的所有内容。

WindsorDependencyResolver.cs

internal sealed class WindsorDependencyResolver : IDependencyResolver
{
    private readonly IWindsorContainer _container;

    public WindsorDependencyResolver(IWindsorContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }

        _container = container;
    }
    public object GetService(Type t)
    {
        return _container.Kernel.HasComponent(t) ? _container.Resolve(t) : null;
    }

    public IEnumerable<object> GetServices(Type t)
    {
        return _container.ResolveAll(t).Cast<object>().ToArray();
    }

    public IDependencyScope BeginScope()
    {
        return new WindsorDependencyScope(_container);
    }

    public void Dispose()
    {

    }
}

WindsorDependencyScope.cs

internal sealed class WindsorDependencyScope : IDependencyScope
{
    private readonly IWindsorContainer _container;
    private readonly IDisposable _scope;

    public WindsorDependencyScope(IWindsorContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }
        _container = container;
        _scope = container.BeginScope();
    }

    public object GetService(Type t)
    {
        return _container.Kernel.HasComponent(t) ? _container.Resolve(t) : null;
    }

    public IEnumerable<object> GetServices(Type t)
    {
        return _container.ResolveAll(t).Cast<object>().ToArray();
    }

    public void Dispose()
    {
        _scope.Dispose();
    }
}

WatchInstaller.cs

安装程序只是实现IWindsorInstaller接口的类型。该接口有一个名为 Install 的方法。该方法获取容器的一个实例,然后它可以使用流畅的注册 API 注册组件:

public class WatchInstaller : IWindsorInstaller
{
      public void Install(IWindsorContainer container, IConfigurationStore store)
      {
      //Need to Register controllers explicitly in your container
      //Failing to do so Will receive Exception:

      //> An error occurred when trying to create //a controller of type
      //> 'xxxxController'. Make sure that the controller has a parameterless
      //> public constructor.

      //Reason::Basically, what happened is that you didn't register your controllers explicitly in your container. 
      //Windsor tries to resolve unregistered concrete types for you, but because it can't resolve it (caused by an error in your configuration), it return null.
      //It is forced to return null, because Web API forces it to do so due to the IDependencyResolver contract. 
      //Since Windsor returns null, Web API will try to create the controller itself, but since it doesn't have a default constructor it will throw the "Make sure that the controller has a parameterless public constructor" exception.
      //This exception message is misleading and doesn't explain the real cause.

      container.Register(Classes.FromThisAssembly()
                            .BasedOn<IHttpController>()
                            .LifestylePerWebRequest());***
          container.Register(
              Component.For<IWatch>().ImplementedBy<Watch>()
          );
      }
}

最后,我们需要用 Global.asax.cs(Application_Start 方法)中的 Windsor 实现替换默认的依赖解析器并安装我们的依赖:

    private static IWindsorContainer _container;
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        ConfigureWindsor(GlobalConfiguration.Configuration);
    }

    public static void ConfigureWindsor(HttpConfiguration configuration)
    {
        _container = new WindsorContainer();
        _container.Install(FromAssembly.This());
        _container.Kernel.Resolver.AddSubResolver(new CollectionResolver(_container.Kernel, true));
        var dependencyResolver = new WindsorDependencyResolver(_container);
        configuration.DependencyResolver = dependencyResolver;
    }    
于 2013-11-19T12:38:38.883 回答
6

阅读 Mark Seemann 关于webapi 的 windsor 管道的帖子

于 2013-11-12T08:39:05.167 回答
1

我没有直接与温莎城堡合作,但我相信逻辑应该是相似的:

您的WatchControllerctor 应如下所示:

public WatchController(IWatch watch) 
{
    _watch = watch;
}

这就是你inject依赖的地方。

你应该有一个相当于你在其中注册你的WatchController班级的定位器,并告诉它它应该根据你想要的任何东西接收哪个手表......设计/运行时,星期几,随机数......任何有效的东西或你的任何东西需要...

以下代码来自 MVVM-Light,但应阐明上述段落:

static ViewModelLocator()
{
    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

    // This will run in design mode, so all your VS design data will come from here
    if (ViewModelBase.IsInDesignModeStatic)
    {
        SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
    }
    // This will run REAL stuff, in runtime
    else
    {
        SimpleIoc.Default.Register<IDataService, DataService>();
    }

    // You register your classes, so the framework can do the injection for you
    SimpleIoc.Default.Register<MainViewModel>();
    ...
}
于 2013-11-11T11:40:27.627 回答