How to use Microsoft Data Service OData with Unity

If you want to use Unity with a Microsoft Data Service, you need to setup your ioc container once and the perfect time to do it is in the startup. OData service doesn’t have global.asax, neither does it have a ServiceHostFactory where you could setup your container.

With Microsoft Data Service (OData) you want to setup your Unity container with the method CreateDataSource which is available since you must inherit from DataService.

public class MyDataService : DataService<MyContext>
    public UnityContainer Container { get; set; }

    public static void InitializeService(DataServiceConfiguration config)
        config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
        config.UseVerboseErrors = true;
    protected override ODataDbContext CreateDataSource()
        Container = new UnityContainer();
        return new MyDataSourceContext(Container.Resolve<IMyInterface>());

As you can see, you just need to define your UnityContainer as a property to your class (or you could use an attribute) and then initialize it inside CreateDataSource method. Not only you can initialize your container here, but you can override the one defined in DataSerivce to use yours (MyDataSourceContext) which use unity for its parameters.

So, if you have a context for test and for your Data Service, then you could simply put any of the two in the class signature : public class MyDataService : DataService, and defined the real context to use later in the override method. The main advantage is that you can inject with Unity (or any ioc container you use) classes to you context.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

2 thoughts on “How to use Microsoft Data Service OData with Unity

  1. Pingback: Patrick Desjardins’ Blog ยป How to use Mi crosoft Data Service OData with Unity | Ra Puke Moana

  2. Hi Patrick

    Can you share full implementation. Actually I am not able to map what should be in svc file for such case.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.