WebApi 2 -cant determined DataProtection.IDataProtector Dependency Injection with structuremap - asp.net-web-api

I'm using this beriliant project for base of my MVC project.
But when I use WebAPI for project there is problem in IDataProtector injection.
I redesign base and upload here, and add a console project for testing authorizing with WebAPI.
This is structuremap initialization :
private static readonly Lazy<Container> _containerBuilder =
new Lazy<Container>(initStructureMap, LazyThreadSafetyMode.ExecutionAndPublication);
public static IContainer Container
{
get { return _containerBuilder.Value; }
}
return new Container(ioc =>
{
ioc.For<IUnitOfWork>().HybridHttpOrThreadLocalScoped().Use(() => new DbContext());
ioc.For<IDataSerializer<AuthenticationTicket>>().Use<TicketSerializer>();
ioc.For<ISecureDataFormat<AuthenticationTicket>>().Use<SecureDataFormat<AuthenticationTicket>>();
});
and in WebApiConfig class DI is like this:
var container = StructuremapMvc.Container;
GlobalConfiguration.Configuration.Services.Replace(
typeof(IHttpControllerActivator), new StructureMapHttpControllerActivator(container));
in my startup I create dataprotector with IAppBuilder :
public void ConfigureAuth(IAppBuilder app)
{
StructuremapMvc.Container.Configure(config =>
{
config.For<IDataProtectionProvider>()
.HybridHttpOrThreadLocalScoped()
.Use(() => app.GetDataProtectionProvider());
});
}
It start after WebApiConfig and IDataProtection not work in WebApi. my ServiceLayer is in separate project and DataProtection need to inject there.

you need add two class to your project :
1-StructureMapDependencyScope Class
using StructureMap;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dependencies;
namespace Project.Helpers
{
public class StructureMapDependencyScope : IDependencyScope
{
protected readonly IContainer Container;
public StructureMapDependencyScope(IContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.Container = container;
}
public void Dispose()
{
this.Container.Dispose();
}
public object GetService(Type serviceType)
{
if (serviceType == null)
{
return null;
}
try
{
return serviceType.IsAbstract || serviceType.IsInterface
? this.Container.TryGetInstance(serviceType)
: this.Container.GetInstance(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
return this.Container.GetAllInstances(serviceType).Cast<object>();
}
}
}
2-StructureMapDependencyResolver Class
using StructureMap;
using System.Web.Http.Dependencies;
namespace Project.Helpers
{
public class StructureMapDependencyResolver : StructureMapDependencyScope, IDependencyResolver
{
public StructureMapDependencyResolver(IContainer container)
: base(container)
{
}
public IDependencyScope BeginScope()
{
IContainer child = this.Container.GetNestedContainer();
return new StructureMapDependencyResolver(child);
}
}
}
at the end replace this code with yours in WebApiConfig Class:
// IoC Config
var container = SmObjectFactory.Container;
// Web API configuration and services
config.DependencyResolver = new StructureMapDependencyResolver(container);
read more about Dependency Injection in ASP.NET MVC 4 and Web API by StructureMap here.

You need to explicitly register implementation of IDataProtector in the container.
Sample configuration might looks like this:
ioc.For<IDataProtector>().Use(() => new DpapiDataProtectionProvider().Create("ASP.NET Identity"));
ioc.For<ITextEncoder>().Use<Base64UrlTextEncoder>();
Bear in mind that this specific configuration might not suit your exact needs.
Hope this helps!

Related

Autofac DI wiring up issue in webapi asp.net project

Having an issue getting a service instance in my controller. Followed the documentation from autofac's website but still getting an error. "None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MyAssembly.Controllers.HeartBeatController' can be invoked with the available services and parameters:\r\nCannot resolve parameter 'MyAssembly.IO.IConfig config' of constructor 'Void .ctor(MyAssembly.IO.IConfig)'."
Here is my Global.asax file
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
var builder = new ContainerBuilder();
var config = GlobalConfiguration.Configuration;
WebApiConfig.Register(config);
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
var container = builder.Build();
BuildServices(builder);
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
config.EnsureInitialized();
log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
}
private void BuildServices(ContainerBuilder builder)
{
builder.RegisterType<Config>().As<IConfig>().InstancePerRequest();
}
}
And here is my interface definition and class. Which is defined in the same assembly.
public interface IConfig
{
string GetSetting(string key);
T GetSetting<T>(string key);
}
public class Config : IConfig
{
public string GetSetting(string key)
{
return ConfigurationManager.AppSettings[key];
}
public T GetSetting<T>(string key)
{
var setting = GetSetting(key);
return setting != null ? (T)System.Convert.ChangeType(setting, typeof(T)) : default(T);
}
}
This is so ridiculous but I failed to build the services before the container. Oversight on my part and the below works.
BuildServices(builder);
var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
config.EnsureInitialized();

"The type IUnitOfWork does not have an accessible constructor" with Umbraco 6.1, UmbracoApiController (Web API) & Dependency Injection (Unity)

I am using Umbraco 6.1 with an UmbracoApiController which has a IUnitOfWork injected into it's constructor. To inject the dependencies, I am using Unity, like I have in the past with standard Web API projects. Normally, I set unity up in the Global.asax.cs. As Umbraco does not have this I have created my own UmbracoEvents handler, which inherits from IApplicationEventHandler, and has the methods:
OnApplicationInitialized
OnApplicationStarting
OnApplicationStarted
ConfigureApi
In the OnApplicationStarted method I set up my EF database, db initializer etc and call ConfigureApi to set up Unity. My OnApplication Started and ConfigureApi methods looks like this:
public void OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
_applicationContext = applicationContext;
_umbracoApplication = umbracoApplication;
_contentService = ApplicationContext.Current.Services.ContentService;
this.ConfigureApi(GlobalConfiguration.Configuration);
Database.SetInitializer(null);
PropertySearchContext db = new PropertySearchContext();
db.Database.Initialize(true);
}
private void ConfigureApi(HttpConfiguration config)
{
var unity = new UnityContainer();
unity.RegisterType<PropertiesApiController>();
unity.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
config.DependencyResolver = new IoCContainer(unity);
}
My Controller code:
public class PropertiesApiController : UmbracoApiController
{
private readonly IUnitOfWork _unitOfWork;
public PropertiesApiController(IUnitOfWork unitOfWork)
{
if(null == unitOfWork)
throw new ArgumentNullException();
_unitOfWork = unitOfWork;
}
public IEnumerable GetAllProperties()
{
return new[] {"Table", "Chair", "Desk", "Computer", "Beer fridge"};
}
}
My Scope Container/IoC Container code: (as per http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver)
public class ScopeContainer : IDependencyScope
{
protected IUnityContainer container;
public ScopeContainer(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public object GetService(Type serviceType)
{
if (container.IsRegistered(serviceType))
{
return container.Resolve(serviceType);
}
else
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (container.IsRegistered(serviceType))
{
return container.ResolveAll(serviceType);
}
else
{
return new List<object>();
}
}
public void Dispose()
{
container.Dispose();
}
}
public class IoCContainer : ScopeContainer, IDependencyResolver
{
public IoCContainer(IUnityContainer container)
: base(container)
{
}
public IDependencyScope BeginScope()
{
var child = this.container.CreateChildContainer();
return new ScopeContainer(child);
}
}
My IUnitOfWork code:
public interface IUnitOfWork : IDisposable
{
GenericRepository<Office> OfficeRepository { get; }
GenericRepository<Property> PropertyRepository { get; }
void Save();
void Dispose(bool disposing);
void Dispose();
}
My UnitOfWork implementation:
public class UnitOfWork : IUnitOfWork
{
private readonly PropertySearchContext _context = new PropertySearchContext();
private GenericRepository<Office> _officeRepository;
private GenericRepository<Property> _propertyRepository;
public GenericRepository<Office> OfficeRepository
{
get
{
if (this._officeRepository == null)
{
this._officeRepository = new GenericRepository<Office>(_context);
}
return _officeRepository;
}
}
public GenericRepository<Property> PropertyRepository
{
get
{
if (this._propertyRepository == null)
{
this._propertyRepository = new GenericRepository<Property>(_context);
}
return _propertyRepository;
}
}
public void Save()
{
_context.SaveChanges();
}
private bool disposed = false;
public virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
I have used unity/DI with MVC4/WebAPI controllers and this implementation of UnitOfWork many times before without issue, so I'm thinking it's Umbraco specific.
I have also debugged the application and made sure that it hits OnApplicationStarted and that its parameters are not null.
The GetAllProperties method in the controller is just a test method to make sure it is all working fine, however, when I try and access this action I get the error:
"The type IUnitOfWork does not have an accessible constructor"
Does anyone have experience with using Umbraco 6.1 and it's UmbracoApiController with dependency injection/Unity?
Also, on an unrelated note, is there a way to return JSON instead of XML in the action? In Web API you would just define the formatter in the WebApi.config but there is none in Umbraco.
Thanks,
Justin
In case you haven't found a solution to your problem? Download this nuget package and right after building your unity container:
GlobalConfiguration.Configuration.DependencyResolver =
new Unity.WebApi.UnityDependencyResolver(Bootstrapper.Container);
Notice the namespace which is different than Unity.Mvc4.UnityDependencyResolver.

SignalR + Dependency Injection Questions

I am using SignalR in my MVC3 application, and since I have implemented StructureMap Dependency Injection on my controllers I would like to do the same in my hub, but I can't seem to get it working.
Please tell me what's wrong with my codes below:
SignalRSmDependencyResolver.cs
public class SignalRSmDependencyResolver : DefaultDependencyResolver
{
private IContainer _container;
public SignalRSmDependencyResolver(IContainer container)
{
_container = container;
}
public override object GetService(Type serviceType)
{
object service = null;
if (!serviceType.IsAbstract && !serviceType.IsInterface && serviceType.IsClass)
{
// Concrete type resolution
service = _container.GetInstance(serviceType);
}
else
{
// Other type resolution with base fallback
service = _container.TryGetInstance(serviceType) ?? base.GetService(serviceType);
}
return service;
}
public override IEnumerable<object> GetServices(Type serviceType)
{
var objects = _container.GetAllInstances(serviceType).Cast<object>();
objects.Concat(base.GetServices(serviceType));
return objects;
}
}
SignalRExtensionsRegistry.cs
public class SignalRExtensionsRegistry : Registry
{
public SignalRExtensionsRegistry()
{
For<IDependencyResolver>().Add<SignalRSmDependencyResolver>();
}
}
IoC.cs
public static class IoC {
public static IContainer Initialize() {
var container = BootStrapper.Initialize();
container.Configure(x =>
{
x.For<IControllerActivator>().Singleton().Use<StructureMapControllerActivator>();
});
return container;
}
}
public class StructureMapControllerActivator : IControllerActivator {
public StructureMapControllerActivator(IContainer container) {
_container = container;
}
private IContainer _container;
public IController Create(RequestContext requestContext, Type controllerType) {
IController controller = DependencyResolver.Current.GetService(controllerType) as IController;
return controller;
}
}
AppStart_Structuremap.cs
[assembly: WebActivator.PreApplicationStartMethod(typeof(StoreUI.AppStart_Structuremap), "Start")]
namespace MyNameSpace {
public static class AppStart_Structuremap {
public static void Start() {
var container = (IContainer) IoC.Initialize();
DependencyResolver.SetResolver(new StructureMapDependenceyResolver(container));
AspNetHost.SetResolver(new StructureMapDependencyResolver(container));
}
}
}
NotificationsHub.cs
[HubName("notificationsHub")]
public class NotificationsHub : Hub
{
#region Declarations
private readonly IUserService userService;
#endregion
#region Constructor
public NotificationsHub(IUserService userService)
{
this.userService = userService;
}
#endregion
public void updateServer(string message)
{
Clients.updateClient(message);
}
}
Thanks
Getting Structuremap into SignalR is actually pretty easy. First you want to create your own resolver:
StructureMap Resolver
Usings:
using SignalR.Infrastructure;
using StructureMap;
Class:
public class StructureMapResolver : DefaultDependencyResolver
{
private IContainer _container;
public StructureMapResolver(IContainer container)
{
_container = container;
}
public override object GetService(Type serviceType)
{
object service = null;
if (!serviceType.IsAbstract && !serviceType.IsInterface && serviceType.IsClass)
{
// Concrete type resolution
service = _container.GetInstance(serviceType);
}
else
{
// Other type resolution with base fallback
service = _container.TryGetInstance(serviceType) ?? base.GetService(serviceType);
}
return service;
}
public override IEnumerable<object> GetServices(Type serviceType)
{
var objects = _container.GetAllInstances(serviceType).Cast<object>();
return objects.Concat(base.GetServices(serviceType));
}
}
The idea here is to try and use your container to resolve the dependencies, if you do not have the dependency wired up, pass it through to the default resolver. This way you don't have to worry about all of the other dependencies in SignalR and can focus only on the stuff you want to inject into (Hubs, ConnectionIdFactory, MessageBus, etc.).
Bindings for Resolver and Hub
Next you will want to register this in your container (i like using registries):
Usings:
using SignalR.Infrastructure;
using StructureMap.Configuration.DSL;
Class:
public class ExtensionsRegistry : Registry
{
public ExtensionsRegistry()
{
For<IDependencyResolver>().Add<StructureMapResolver>();
}
}
Resolver Replacement
Finally you will want to tell SignalR to use your resolver instead of the default:
Global::Application_Start or WebActivator::Pre_Start
Usings:
using SignalR.Hosting.AspNet;
using SignalR.Infrastructure;
Application_Start:
// Make sure you build up the container first
AspNetHost.SetResolver(StructureMap.ObjectFactory.GetInstance<IDependencyResolver>());
Silly Hub with injected dependencies
Now you can just inject any dependencies your container knows about into the hubs themselves:
[HubName("defaultHub")]
public class DefaultHub : Hub, IDisconnect
{
private readonly IRepository _repo;
public DefaultHub(IRepository repo)
{
_repo = repo;
}
public void Connect()
{
Caller.setUser(Context.ConnectionId);
Clients.addMessage(string.Format("{0} has connected", Context.ConnectionId));
}
public void MessageSender(string message)
{
Caller.addMessage(_repo.RepositoryMessage());
Clients.addMessage(message);
}
public Task Disconnect()
{
var clientId = this.Context.ConnectionId;
return Task.Factory.StartNew(() => { Clients.addMessage(string.Format("{0} has disconnected", clientId)); });
}
}
Have you followed the instructions here:- https://github.com/SignalR/SignalR/wiki/Extensibility ?
You'll need to use AspNetHost.SetResolver.
I know this is an old thread, but for those who are wondering where is the AspNetHost.SetResolver in the newer version of signalR, you can use this in the App_Start StructuremapMvc.cs:
public static void Start() {
IContainer container = IoC.Initialize();
GlobalHost.DependencyResolver = new SignalRSmDependencyResolver(container); // for signalR
DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(container);
}
Add something like this to a file in your App_Start folder. This code snippet is for Ninject, so just replace AspNetHost.SetResolver()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Ninject;
using SignalR.Hosting.AspNet;
using SignalR.Infrastructure;
using SignalR.Ninject;
using Web.Models;
[assembly: WebActivator.PreApplicationStartMethod(typeof(Web.App_Start.NinjectSignalR), "Start")]
namespace Web.App_Start
{
public static class NinjectSignalR
{
public static void Start()
{
IKernel kernel = CreateKernel();
// switch this line to the structuremap resolver
AspNetHost.SetResolver(new NinjectDependencyResolver(kernel));
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
RegisterServices(kernel);
return kernel;
}
private static void RegisterServices(IKernel kernel)
{
// add your services here
//kernel.Bind<IRepository>().To<Repository>();
}
}
}

How should the GetService method in IDependencyResolver implementation for Unity look like?

I'd like to use Unity as an IoC container for an ASP.NET MVC 3 app but am having trouble with my UnityDependecyResolver class. It currently looks like this (copied from somewhere on the web as I don't think Unity itself comes with this):
public class UnityDependencyResolver : IDependencyResolver
{
readonly IUnityContainer _container;
public UnityDependencyResolver(IUnityContainer container)
{
this._container = container;
}
public object GetService(Type serviceType)
{
try
{
return _container.Resolve(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return _container.ResolveAll(serviceType);
}
catch
{
return new List<object>();
}
}
}
However, I get this runtime error when trying to visit any controller:
The IControllerFactory 'System.Web.Mvc.DefaultControllerFactory' did not return a controller for the name 'Account'.
This StructureMap article suggests that I should amend the GetService method, however, I'm quite new to both MVC and Unity and I'm not sure how exactly should it look like.
Have a look at the Unity.MVC project on codeplex.
This is my implementation and for me it works
public class UnityResolver : IDependencyResolver
{
private readonly IUnityContainer _container;
public UnityResolver(IUnityContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
if (typeof(IController).IsAssignableFrom(serviceType))
{
return _container.CreateChildContainer().Resolve(serviceType);
}
if (_container.IsRegistered(serviceType))
{
return _container.CreateChildContainer().Resolve(serviceType);
}
return null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.CreateChildContainer().ResolveAll(serviceType);
}
}

How to use property injection in unity and asp.net mvc3?

I would like to use property injection in an MVC3 application. I have configured Unity 2 as a DI container and everything works just fine by constructor injection but I can't figure out how to use property injection. I marked properties with the [Dependency] attribute but it doesn't work.
public class UnityDependencyResolver : IDependencyResolver
{
IUnityContainer _container;
public UnityDependencyResolver(IUnityContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
try
{
return _container.Resolve(serviceType);
}
catch (Exception)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return _container.ResolveAll(serviceType);
}
catch (Exception)
{
return new List<object>();
}
}
}
In Global.asax I have the following:
var container = new UnityContainer();
var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Configure(container);
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
Any help is appreciated.

Resources