F#Web API中的IDependencyResolver接口实现

时间:2015-06-16 16:38:00

标签: dependency-injection f# c#-to-f#

我正在用F#重写一个C#ASP.NET Web API应用程序。我完成了模型和控制器,然后我转到实现IDependencyResolverMyDependencyResolver

我在实现GetService方法时遇到问题,其在C#中的签名是:

object GetService(System.Type serviceType)

所以我需要返回obj并将System.Type作为参数。

这是我到目前为止在F#中所拥有的:

type MyDependencyResolver() =
    interface System.Web.Http.Dependencies.IDependencyResolver with
        member this.BeginScope() : IDependencyScope =
            this :> IDependencyScope

        member this.GetService(serviceType:Type) : obj =

            if (serviceType = typeof<Controllers.HomeController>) then
                let homeController = new Controllers.HomeController(arg1, arg2, arg3, arg4)
                homeController :> obj
            // ???
            elif (serviceType = typeof<_>) then
                null           

        member this.GetServices (serviceType: Type) :IEnumerable<obj> =
            let x = new List<obj>()
            x :> IEnumerable<obj>

        member this.Dispose() =
            ()

因此,如果serviceType的类型为HomeController,我想返回HomeController的实例,如果它是任何其他类型的实例,我想返回null。我如何在F#中做到这一点?

编辑:

C#中的

GetService方法:

 public object GetService(Type serviceType)
 {
    if (serviceType == typeof(Controllers.HomeController)){
        return new Controllers.HomeController(arg1, arg2, arg3, arg4);
    }
    return null;
 }

1 个答案:

答案 0 :(得分:1)

您可以使用Activator.CreateInstance(serviceType)但是从哪里获取构造函数参数?

在我的项目中,我使用Unity,其配置如下:

let private ConfigureUnity (config : HttpConfiguration) =
        let rec unityResolver (container : IUnityContainer) =
            { new IDependencyResolver with
                member this.BeginScope() =
                    unityResolver(container.CreateChildContainer()) :> IDependencyScope
                member this.GetService serviceType =
                    try container.Resolve(serviceType) with
                        | :? ResolutionFailedException -> null
                member this.GetServices serviceType = 
                    try container.ResolveAll(serviceType) with
                        | :? ResolutionFailedException -> Seq.empty
                member this.Dispose() = container.Dispose()
            }

        config.DependencyResolver <- (new UnityContainer())
            .RegisterType<IFoo, FooImplementation>(new HierarchicalLifetimeManager())
            .RegisterType<IBar, BarImplementation>(new HierarchicalLifetimeManager())
            |> unityResolver

然后自动解析类(例如您的控制器),Unity将为您创建依赖项(构造函数参数)。使用其他依赖注入框架应该很简单。