Search code examples
c#asp.net-mvc-4asp.net-web-apiwindows-services

Web Api and external event handling


I've got a windows service, and I want to expose a web api on this service so our users can interact with the service via http.

I understand how to do a self host web api (http://www.asp.net/web-api/overview/hosting-aspnet-web-api/self-host-a-web-api), now my main problem is how to interface my ApiController with the class it will be executed from, so that when an http request is processed, an event is triggered, and something happens outside of the ApiController.

Based on the following example, how can I register my event handler UserRegistered in my service class ?

Web API Controller

public class MyController : ApiController
    {
        public delegate void OnPostRegister(Profile user);

        public event OnPostRegister UserRegistered;

        public void PostStream(Profile user)
        {
            try
            {
                IProfileBuilder builder = new ProfileBuilder();
                builder.RegisterProfile(user);

                if (UserRegistered!= null)
                {
                    UserRegistered(user);
                }

            }
            catch (Exception ex)
            {
                throw new HttpException(500, ex.Message);
            }
        }

Service Class

public partial class Service1 : ServiceBase
{
    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        //initialize web api
        var config = new HttpSelfHostConfiguration("http://localhost:8080");

        config.Routes.MapHttpRoute(
            "API Default", "api/{controller}/{id}",
            new { id = RouteParameter.Optional });

        using (var server = new HttpSelfHostServer(config))
        {
            server.OpenAsync().Wait();
        }

        //Load registered profiles
    }

    protected override void OnStop()
    {
    }
}

Solution

  • I don't think you can access the instance of the controller to subscribe to an event directly; I think you probably want a loosely coupled event handler; I was going to suggest the EventAggregator but that is part of Prism which is more for WPF although you could extract it. I did find this which looks like it could solve your issue.

    http://blogs.taiga.nl/martijn/2011/07/28/loosely-coupled-events-in-net-and-harvesting-open-source-projects/