繁体   English   中英

如何将依赖项传递给WCF restful服务

[英]How to pass dependencies to a WCF restful service

我是Rest服务的新手。 我对这个主题做了相当多的研究,但仍然没有清楚地理解。 希望有人向我表明这一点。 提前致谢。

我的客户端将通过url在我的服务类上执行一个方法。 所有我理解的是客户打电话

localhost/service/get/customers

在我的休息服务中,我有像IRepository这样的依赖项,以便我可以访问数据库并获取记录。 如果我在客户端调用此构造函数时使用构造函数注入?

看起来我需要使用服务定位器来获取我需要它的方法中的IRepository

这不违反OOP原则吗? 没有DI,测试容易吗?

任何人都可以澄清一下。

对于任何服务,我们如何期望客户知道什么是IRepository它有什么方法? 是不是内部实现目的我们需要暴露给客户端吗? 他为什么要为此烦恼呢? 我不能只提供Uri调用哪种方法(localhost / service / Products)和完成工作。

如果您提供任何实例,我将不胜感激。

非常感谢。

不,如果您要解决方法中的依赖关系,它不会违反OOP原则。 但是没有必要,你可以使用Instance Provider和ServiceHostFactory在WCF中使用构造函数Dependency Injection ,这个问题也有很好的例子。

如果您是自托管服务,它将更加简单,因为它只需要实现IInstanceProviderServiceHost 假设您使用带有IDependency参数的构造函数的Service服务:

public class CustomInstanceProvider : IInstanceProvider, IContractBehavior
{
    private readonly IDependency dependency;

    public CustomInstanceProvider(IDependency dependency)
    {
        this.dependency = dependency;
    }

    public object GetInstance(InstanceContext instanceContext)
    {
        // Here you are injecting dependency by constructor
        return new Service(dependency);
    }

    public object GetInstance(InstanceContext instanceContext, Message message)
    {
        return this.GetInstance(instanceContext);
    }
    public void ReleaseInstance(InstanceContext instanceContext, object instance)
    {

    }

    public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
    {

    }

    public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
    {
        dispatchRuntime.InstanceProvider = this;
    }

    public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {

    }

    public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {

    }
}

public class CustomServiceHost : ServiceHost
{
    public CustomServiceHost(IDependency dependency, Type serviceType, params Uri[] baseAddresses)
        : base(serviceType, baseAddresses)
    {
        foreach (var cd in this.ImplementedContracts.Values)
        {
            cd.Behaviors.Add(new CustomInstanceProvider(dependency));
        }
    }
}

然后在创建服务时,使用CustomServiceHost

var serviceHost = new CustomServiceHost(dependency, typeof(Service), uris);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM