使用Castle Windsor在WebAPI中进行依赖注入

Sumit Deshpande

我想使用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的情况下,有人可以为我提供实现依赖注入的步骤吗?提前致谢!

Sumit Deshpande

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

第一步是使用nugetWebApi解决方案中安装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中的Windsor实现替换默认的依赖项解析器(Application_Start方法),并安装我们的依赖项:

    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;
    }    

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

使用统一框架在MVC 3中进行依赖注入

来自分类Dev

使用服务别名进行依赖项注入

来自分类Dev

使用CDI在简单的Java程序中进行依赖注入

来自分类Dev

使用Castle Windsor在WebAPI中进行依赖注入

来自分类Dev

WPF ViewModel中的Castle Windsor构造函数注入

来自分类Dev

使用编译时编织进行依赖注入?

来自分类Dev

使用Ninject OWIN中间件在OWIN启动中进行依赖注入UserStore

来自分类Dev

使用ninject在unittest中进行属性注入

来自分类Dev

使用DBContext进行依赖注入的后果

来自分类Dev

如何使用Ember CLI在Ember中进行依赖项注入?

来自分类Dev

使用Azure WebJobs SDK进行依赖注入?

来自分类Dev

如何使用依赖注入进行测试?

来自分类Dev

使用反射进行Ninject依赖注入

来自分类Dev

如何使用ES6在AngularJs中进行依赖注入?

来自分类Dev

使用Castle-Windsor在MVC4中使用HttpClient的方式

来自分类Dev

使用EntityMenager进行Symfony依赖注入

来自分类Dev

Java:使用Bouncy Castle进行PGP加密

来自分类Dev

使用CDI在简单的Java程序中进行依赖注入

来自分类Dev

使用统一框架在MVC 3中进行依赖注入

来自分类Dev

在Windows窗体应用程序中使用Castle Windsor

来自分类Dev

使用ninject在unittest中进行属性注入

来自分类Dev

如何使用Ember CLI在Ember中进行依赖项注入?

来自分类Dev

Castle.Windsor使用Dapper实例化错误版本的SqlConnection

来自分类Dev

使用Castle Windsor将具有不同实现的列表的对象作为构造函数参数进行解析

来自分类Dev

在ASP.NET MVC 5中使用ControllerFactory在控制器的构造函数中进行依赖项注入

来自分类Dev

使用 Castle Windsor fluent API 注册实现多个接口的组件

来自分类Dev

使用 Castle Windsor 在 QueryBus 中查找查询处理程序

来自分类Dev

Castle Windsor 具体类型解析和属性注入

来自分类Dev

使用 WebApi 在 Angular 中进行 CRUD 操作

Related 相关文章

  1. 1

    使用统一框架在MVC 3中进行依赖注入

  2. 2

    使用服务别名进行依赖项注入

  3. 3

    使用CDI在简单的Java程序中进行依赖注入

  4. 4

    使用Castle Windsor在WebAPI中进行依赖注入

  5. 5

    WPF ViewModel中的Castle Windsor构造函数注入

  6. 6

    使用编译时编织进行依赖注入?

  7. 7

    使用Ninject OWIN中间件在OWIN启动中进行依赖注入UserStore

  8. 8

    使用ninject在unittest中进行属性注入

  9. 9

    使用DBContext进行依赖注入的后果

  10. 10

    如何使用Ember CLI在Ember中进行依赖项注入?

  11. 11

    使用Azure WebJobs SDK进行依赖注入?

  12. 12

    如何使用依赖注入进行测试?

  13. 13

    使用反射进行Ninject依赖注入

  14. 14

    如何使用ES6在AngularJs中进行依赖注入?

  15. 15

    使用Castle-Windsor在MVC4中使用HttpClient的方式

  16. 16

    使用EntityMenager进行Symfony依赖注入

  17. 17

    Java:使用Bouncy Castle进行PGP加密

  18. 18

    使用CDI在简单的Java程序中进行依赖注入

  19. 19

    使用统一框架在MVC 3中进行依赖注入

  20. 20

    在Windows窗体应用程序中使用Castle Windsor

  21. 21

    使用ninject在unittest中进行属性注入

  22. 22

    如何使用Ember CLI在Ember中进行依赖项注入?

  23. 23

    Castle.Windsor使用Dapper实例化错误版本的SqlConnection

  24. 24

    使用Castle Windsor将具有不同实现的列表的对象作为构造函数参数进行解析

  25. 25

    在ASP.NET MVC 5中使用ControllerFactory在控制器的构造函数中进行依赖项注入

  26. 26

    使用 Castle Windsor fluent API 注册实现多个接口的组件

  27. 27

    使用 Castle Windsor 在 QueryBus 中查找查询处理程序

  28. 28

    Castle Windsor 具体类型解析和属性注入

  29. 29

    使用 WebApi 在 Angular 中进行 CRUD 操作

热门标签

归档