Don't miss out Virtual Happy Hour this Friday (April 26).

Try our conversational search powered by Generative AI!

Depenct Injection via constructor in Virtual Roles?


Is it possible to do dependency injection via the constructor in classes that inherits VirtualRoleProviderBase?

I have no problem doing ctor injection in e.g. controller classes etc and I have verified that my implementations are registered before the framework runs EPiServer.Framework.FrameworkInitialization.InitializeVirtualRoles(). But I still get this "No parameterless constructor defined for this object" for my virtual role.

The code works if I use an injected property (like Injected<IMyService> myService { get; set; }) instead, but I would love to go via the constructor if possible!


Feb 18, 2014 14:51


I assume that you're using your virtual role in a Model object? Without much detail I would suggest to try to add a parameterless constructor to your class, which just to make DefaultModelBinder happy.

Am I missing something?


Feb 18, 2014 15:28


No there is no model binding going on.

I just use it like this IPrincipal.IsInRole("MyCustomVirtualRole") to test if the current user is allowed to perform certain operations. For instance, I might use this in a controller action or in an action filter class.

The "no parameterless constructor" exception is thrown right at startup when EPiServer Framework runs its initialization code for registering all the defined virtual roles.

Feb 18, 2014 17:53

There are parts of the API that doesn't support constructor injection. If you still want to have a constructor accepting services for example to use in tests, I suggest you overload the constructor, like so:

public class MyClass
  private IService _service;

  public MyClass() : this(ServiceLocator.Current.GetInstance<IService>()) {}

  public MyClass(IService service)
    _service = service;

There are cases where this won't work, for example if the class is instantiated using the parameterless constructor before the DI container is initialized with the requested service.

Feb 18, 2014 20:31

Thanks Magnus, that's what I suspected. Your solution is fine - slightly more elegant than relying on Injected<IService> in my opinion!

Feb 19, 2014 9:44
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.