Self-host (No IIS or WAS) WCF with service requiring parameters

Hope this is easy. I am wondering if this is possible - perhaps it is not. I am trying to host a WCF service myself (in my example below, it is a console application). The service does not have a default constructor. It only contains a signature constructor with one parameter. I need a service to be able to handle user sessions. I am currently using Ninject DI. Here is a simple code solution I came up with to demonstrate my problem:

using System;
using System.ServiceModel;
using System.ServiceModel.Web;
using Ninject.Modules;

namespace ConsoleApplication1
{
    public class Program
    {
        static void Main()
        {
            using (var webServiceHost = new WebServiceHost(typeof(MyWcf)))
            {
                var webHttpBinding = new WebHttpBinding();
                var uri = new Uri("http://localhost:8000/");
                webServiceHost.AddServiceEndpoint(typeof(IMyWcf), webHttpBinding, uri);
                webServiceHost.Open();
                Console.WriteLine("Service is ready...");
                Console.ReadKey();
            }
        }
    }

    [ServiceContract]
    public interface IMyWcf
    {
        [OperationContract, WebGet(UriTemplate = "")]
        string HelloWorld();
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    public class MyWcf : IMyWcf
    {
        private readonly IMessage _customMessage = new Message("Default Message.");

        public MyWcf(IMessage message)
        {
            _customMessage = message;
        }

        public string HelloWorld()
        {
            return _customMessage.Text;
        }
    }

    public interface IMessage
    {
        string Text { get; }
    }

    public class Message : IMessage
    {
        public Message (string message)
        {
            Text = message;
        }
        public string Text { get; set; }
    }

    public class NinjectSetup : NinjectModule
    {
        public override void Load()
        {
            Bind<IMessage>().To<Message>()
                .WithConstructorArgument("message", "Injected String Message.");
        }
    }
}

      

Obviously, commenting out the parameterized constructor allows the service to start. But that doesn't do me any good. I don't want to use ServiceHostFactory because it seems to require me to have .svc / IIS. Is there a way to get around this? Can I just create a new MyWebServiceHost

one that inherits from WebServiceHost

and override some method that will instantiate for the service?

+3


source to share


1 answer


Using Ruben's suggestion (in the comments) above, I was able to find a working example in the original Ninject.Extensions.Wcf repository.



+1


source







All Articles