没有XML配置的Ninject依赖关系绑定到WCF服务

时间:2019-05-06 03:11:13

标签: wcf dependencies ninject

我正在尝试使用Ninject依赖注入将回调方法绑定到WCF REST服务在软件系统的一种插件模块中运行,而对于任何软件都无法使用SVC文件或webconfig或app.config配置。

WCF服务的接口和实现定义如下:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    string DoWork();
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class Service1 : IService1
{
    private IEventCallback EventCallback { get; set; }

    public Service1(IEventCallback eventCallback)
    {
        EventCallback = eventCallback;
    }

    public string DoWork()
    {
        if (EventCallback != null)
        {
            EventCallback.Send("Testing Event ID");    
        }            

        return "Success";
    }
}

其中IEventCallback和相应的实现定义如下:

public interface IEventCallback
{
    void Send(string eventId);
}

public class EventCallback : IEventCallback
{
    private Action<string> OnSendCustomEventCallBack { get; set; }

    public EventCallback(Action<string> onSendCustomEventCallBack)
    {
        OnSendCustomEventCallBack = onSendCustomEventCallBack;
    }

    public void Send(string eventId)
    {
        if (OnSendCustomEventCallBack != null)
        {
            OnSendCustomEventCallBack(eventId);
        }
    }
}

创建REST服务的代码如下:

public AuthenticatedWebServiceHost(Type type, Uri url, string authenUsername, string authenPassword)
{
    AuthenUsername = authenUsername;
    AuthenPassword = authenPassword;

    IDictionary<string, ContractDescription> desc;

    InitializeDescription(type, new UriSchemeKeyedCollection());
    base.CreateDescription(out desc);
    var val = desc.Values.First();            

    var binding = new WebHttpBinding();
    binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
    binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

    Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
    Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = 
        new CustomUserNamePasswordValidator(AuthenUsername, AuthenPassword);

    AddServiceEndpoint(val.ContractType, binding, url);
}

然后,AuthenticatedWebServiceHost的调用如下:

var eventCallback = new EventCallback(OnSendCustomEventCallBack);   // where OnSendCustomEventCallBack is a defined method   

// How to write codes to use Ninject to inject the callback into the Service?
// kernel.Bind<IEventCallback>().To<??>()

_webServiceHost = new AuthenticatedWebServiceHost(typeof(Service1), new Uri("http://localhost:9000/Events"),
    "admin", "password");

_webServiceHost.Open();

既然我不允许使用XML配置,那么如何编写代码以使用Ninject将回调绑定到WCF服务?

1 个答案:

答案 0 :(得分:0)