Unity Dependency Injection for WCF services - dependency-injection

Can someone direct me to a good example of Unity Dependency Injection for WCF services?
Any blog or msdn article will also help.

This answer gives an example on how to enable DI in WCF with Castle Windsor.
Just replace the IWindsorContainer with an IUnityContainer in the example and you should be all set, although you may also want to change the class names from WindsorXyz to UnityXyz :)

To inject dependencies into WCF services I had to implement a service host factory.
I have found a step-by-step tutorial here.
Basically you have to:
Implement an IInstanceProvider to create services using the container
Implement an IServiceBehavior to set the instance provider in the endpoint dispatcher
Extend ServiceHost to add the new service behavior
Extend ServiceHostFactory to create the new service host

I'm about to give a try to Unity.Wcf library (https://github.com/ViceIce/unity.wcf), at first sight looks pretty good. I've read in this article this:
If you are hosting your WCF service within a Windows Service using a ServiceHost, replace the ServiceHost instance with the custom Unity.Wcf.UnityServiceHost. You will find that the UnityServiceHost takes in a Unity container as its first parameter but is otherwise identical to the default ServiceHost.
As it is my case I'm going to do this...
class Program
{
static void Main(string[] args)
{
// 1st Initialize the Host (Configures Container and Factories)
ServiceHostController.Initialize();
// 2nd Create a URI to serve as the base address.
var baseAddress = new Uri("http://localhost:54321/BlaBlaBla/");
// 3rd Create a UnityServiceHost instance
var myService = new UnityServiceHost(ServiceHostController.UnityContainer, typeof(MyService), baseAddress);
try
{ //etcetera...
And it worked for me, I still have to refactor some things and add features and methods but the starting point works like a charm.
I hope it helps.

Related

Get DataProtectionProvider in MVC 5 for dependecy injection correctly

When trying to create a DataProtectionProvider manually I have stumbled upon the Microsoft documenation to DpapiDataProtectionProvider which says:
Used to provide the data protection services that are derived from the
Data Protection API. It is the best choice of data protection when you
application is not hosted by ASP.NET and all processes are running as
the same domain identity.
A question suddenly arises: What is the best choice when your application IS hosted by ASP.NET?
Searching further, it seems the best choice is to obtain the DataProtectionProvider from OWIN. That can be done in Startup configuration, where you have IAppBuilder and using AppBuilderExtensions located in Microsoft.Owin.Security.DataProtection namespace you can call app.GetDataProtectionProvider().
So far, I am quite satisfied. However, now you want to inject the DataProtectionProvider in a constructor of your class (e.g. a UserManager). I have seen one suggestion where you store the DataProtectionProvider in a static property and then use it where you need, but that seems like a rather wrong solution.
I think a solution similar to the following piece of code would be appropriate (using ninject container):
kernel.Bind<IDataProtectionProvider>()
// beware, method .GetDataProtectionProvider() is fictional
.ToMethod(c => HttpContext.Current.GetOwinContext().GetDataProtectionProvider())
.InRequestScope();
There is a walkthrough that tells you how to register the DataProtectionProvider with Autofac.
builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();
You can also achieve this with Unity with the following line:
container.RegisterType<IDataProtectionProvider>(new InjectionFactory(c => app.GetDataProtectionProvider()));
Where container is
var container = new UnityContainer();
This will allow you to use the DataProtectionProvider in the constructor as follows.
public ApplicationUserManager(IUserStore<ApplicationUser> store, IIdentityMessageService emailService, IDataProtectionProvider dataProtectionProvider)
I prefer this approach over the approach mentioned on this blog post here https://tech.trailmax.info/2014/09/aspnet-identity-and-ioc-container-registration/, simply because it allows you to have the classes that use the DataProtectionProvider in separate libraries if you would like and it is much cleaner.

MVC Single Instance Object

I need to declare an object in MVC app. This object consume memory so I need it to be created once when app start and won't be destroy until recycled. The same instance of the object also should be able accessed across application within controllers.
I have used this object in WCF service by using InstanceContextMode.Single and works great. But how with MVC?
I would implement a Singleton Pattern https://msdn.microsoft.com/en-us/library/ff650316.aspx
If you are using any Dependency injection container then all of them have support for Singleton Instance
As singletons are largely considered an anti-pattern. They make your code hard to test (using mocks and stubs) and create tightly coupled code.
Since this is very bad practice, you are better off using an IoC container (Unity, SimpleIoC, Autofac, etc.) to manage the lifetime of your containers. The Unity 3 IoC container has an ContainerControlledLifetimeManager lifetime manager where objects are created once and the same instance is returned for the lifetime of the container.
In your composition root you could either do (using IMemoryConsumingService interface to avoid tight coupling). Then just inject it into your controllers and services. Example for Unity 3 (other IoC have similar procedure).
MemoryConsumingService service = new MemoryConsumingService();
container.RegisterInstance<IMemoryConsumingService>(service);
or
container.RegisterType<IMemoryConsumingService, MemoryConsumingService(new ContainerControlledLifetimeManager());
Edit:
When you install Unity 3.5 + Unity MVC Bootstraper you are basically ready to go for it.
public class UnityConfig
{
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<IDriver, Driver>(new ContainerControlledLifetimeManager());
// OR
IDriver driver = new Driver();
container.RegisterInstance<IDriver>(driver);
}
}
Inside the RegisterType method you do your registration (please check out the documentation link below, IoC is to complicated to explain it within an simple answer). The newer nugetpackages get you ready to go, without any further changes (except adding registrations). No need to change the Global.asax as it was required in the early years of Unity.

OWIN Service resolution Using Autofac

I have an WebApi application using OWIN and Autofac. Although controllers and parameters get resolved correctly, I would like to be able to use OwinContext.Get<type> to resolve types registered with Autofac. Is that posible?
Already setapp.UseAutofacMiddleware(container); and config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
By example, I registered builder.Register<IAppConfiguration>(c => new AppConfig()); and I'd like to resolve it using owinContext.Get<IAppConfiguration>().
There is no way to get OwinContext.Get<T> to resolve things from Autofac. If you dive into Microsoft.Owin.OwinContext.Get in Reflector, you'll see it's backed entirely by a dictionary of things you register with an environment. It's not dynamic and there's no way (without creating your own IOwinContext implementation) to get it to resolve things either out of the dictionary or out of dependency resolution.
If you are in a DelegatingHandler or an ApiController you will have a reference to the current HttpRequestMessage. Use message.GetDependencyScope() to get the current request-level dependency scope to resolve services.
public HttpResponseMessage SomeControllerAction()
{
var service = this.Request.GetDependencyScope().GetService(typeof(Service));
}
If you have access to the HttpConfiguration then you can use the HttpConfiguration.DependencyResolver to resolve things. Note that resolver will not have per-request dependencies available. Web API tracks request dependency scope with the inbound HttpRequestMessage so be aware of that limitation. There is an FAQ about per-request lifetime scope that can help you through that.
If you're in a place where there's only an IOwinContext, you may need to make use of a package like CommonServiceLocator and the associated Autofac.Extras.CommonServiceLocator. There really isn't a way to get a reference to the current HttpConfiguration or global container just from an IOwinContext. Again, if you go this route, you won't have per-request dependencies available, so be aware.
The IOwinContext.Get uses the Environment dictionary, resolving objects registered directly with Owin, it does not take into account Autofac container.
I managed to do it by accessing the Autofac OwinLifetimeScope in the Environment property and using the scope to resolve the service.
You can access the LifetimeScope using this code
var scope=OwinContext.Get<Autofac.Core.Lifetime.LifetimeScope>("autofac:OwinLifetimeScope");
and then
scope.GetService(type)
You should check for nulls and write it in a better way, as Extension method maybe.
If you have WebAPI in your project, you can simulate a http request like this
var dependencyScope = new AutofacWebApiDependencyScope(owinContext.GetAutofacLifetimeScope());
var myService = dependencyScope.GetService(typeof(MyService));

Two MVC applications using ninject to the same services and repositories

I am setting up a n tier system and have chosen to use ninject as the IoC/Di container. As part of this application I have got two MVC front ends. One is for the end user and the other is for the Administraion and configuration. I have chose two fron ends so that views & controllers e.t.c are contained and will make thinks a little easier to manage when I get to 100+ containers.
Anyway... What I want to know is?
Can I make my startup project the Admin application and instanciate Ninject e.t.c from here then when my second MVC application is called by the user it can use the same Ninject container which has alread been instantiated?
I hope this make sense to you all.
Also as an aside, does anyone know how to use Ninject to inject the DBcontext connection string/name?
You could create separate class library (called maybe SharedConfiguration?) with class
public static class NinjectSharedConfiguration
{
public static void RegisterServices(IKernel kernel)
{
kernel.Bind<MyDbContext()
.ToSelf()
.InRequestScope()
.WithConstructorArgument("nameOrConnectionString", "server = .;");
}
}
And make call to this method from both projects

Where's Simple Injector's equivalent of StructureMap's ObjectFactory

I am in the process of migrating from StructureMap to Simple Injector in a ASP.NET MVC3 application.
I am using the MVC3 extension for controller DI, but I am running into an issue with trying to replace the static aspects of StructureMap. We have calls to
StructureMap.ObjectFactory.GetInstance<Interface>()
throughout different layers of the app. It does not look like Simple Injector has a way to do that.
Am I missing something? Or is Simple Injector not applicable for my application?
Please advise and thanks in advance.
Allowing the application to directly access the container is considered to be bad practice. It is an form of the Service Locator anti-pattern.
Because this is considered to be a bad thing, Simple Injector does not contain anything like StructureMap's ObjectFactory.GetInstance. And as a matter of fact, the author of StructureMap is considering the removal of the ObjectFactory API in a furure release of StructureMap.
However, nothing stops you from storing the SimpleInjector.Container instance in a static field and let the application use this:
// Service Locator implementation in low application layer.
public static class ObjectFactory
{
private static SimpleInjector.Container container;
public static void SetContainer(Container container)
{
ObjectFactory.container = container;
}
public static T GetInstance<T>() where T : class
{
return container.GetInstance<T>();
}
}
In Composition root:
public static void Initialize()
{
var container = new Container();
InitializeContainer(container);
DependencyResolver.SetResolver(
new SimpleInjectorDependencyResolver(container));
// Set the service locator here
ObjectFactory.SetContainer(container);
}
So there is no limitation in the Simple Injector that prevents you from doing this, but frankly, you are already witnessing one of the reasons why Service Locator is a bad thing: you switched containers and now you have to change application code.
Perhaps for now it is easiest for you to save the container in a static field (as shown in the example above), but please take the time to understand why this pattern is bad, and do refactor away from this pattern towards dependency injection (and especially constructor injection).

Resources