How to use Microsoft Data Service OData with Unity
Posted on: 2013-06-03
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(); Bootstrapper.Initialise(Container); 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.