簡體   English   中英

使用Castle Windsor在WebAPI中進行依賴注入

[英]Dependency Injection in WebAPI with Castle Windsor

我想使用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的情況下,任何人都可以為我提供實現依賴注入的步驟嗎? 提前致謝!

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

閱讀Mark Seemann關於webapi的溫莎管道的文章

我沒有直接與Castle Windsor合作,但我相信邏輯應該是相似的:

您的WatchController ctor應該如下所示:

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

這就是你inject依賴的地方。

你應該擁有一個Locator,你可以在其中注冊你的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>();
    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM