ninject依赖关系绑定到无XML配置的WCF服务



我正在尝试使用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);
        }
    }
}

创建休息服务的代码如下:

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服务?

我最终通过引用是否可以通过服务类型的实例实例化WebServiceHost来找出解决方案,而无需无参数构造函数?不使用ninject。

最新更新