I can't seem to figure out how to get dependency injection to work in a custom membership provider. I'm aware that the membership provider base class is managed deep in ASP.NET, but there should be some way to get dependency injection to work on private data members.
I'm using Unity and see this issue only in my membership and role providers
my issue is two fold:
The application complains that it doesn't have a parameterless
constructor for "MyMembershipProvider"
even if I try this: https://stackoverflow.com/a/9815425/595335, security service is null in the ValidateUser method
public class MyMembershipProvider : MembershipProvider
{
public ISecurityService securityService;
public MyMembershipProvider(ISecurityService securityService)
{
this.securityService = new SecurityService();
}
public override bool ValidateUser(string username, string password)
{
User user = securityService.GetUserByUsername(username);
...ommited...
}
It may not be as ideal, but you might need to use property injection instead of constructor injection.
The problem is that your provider is created by a static class. Since static classes are not "instantiated" and live for the lifetime of the app, there is no way to allow your DI framework to instantiate a static class.
There are potential workarounds, but you can't use constructor injection. These workarounds are also brittle and overly complex. In short, it's a PITA and is just not worth the effort. You would probably save yourself a lot of headache by either forgettinga bout DI in a membership provider, or forgetting about using Membership and roll a custom IIdentity and IPrincipal solution.
Related
I have tried most of the examples in the Google Results, Stackoverflow and in AutoMapper. But was not able to get the IValueResolverdependancy injection to work.
I have below service
public class StorageService : IStorageService
{
private readonly BlobServiceSettings _blobServiceSettings;
public StorageService(IOptions<BlobServiceSettings> blobServiceSettings)
{
_blobServiceSettings = blobServiceSettings.Value;
}
// some methods I need
}
This is my profile
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Building, BuildingEnvelope>(MemberList.None)
.ForMember(dest => dest.ImageUrl, opt => opt.ResolveUsing<BuildingImageUrlResolver>());
}
}
this is my IValueResolver
public class BuildingImageUrlResolver : IValueResolver<Building, BuildingEnvelope, string>
{
private readonly IStorageService _storageService;
public BuildingImageUrlResolver(IStorageService storageService)
{
_storageService = storageService;
}
public string Resolve(Building entity, BuildingEnvelope envelope, string member, ResolutionContext context)
{
return _storageService.MyMethod(entity.ImageFileName);
}
}
I get the below error in my inner exception
No parameterless constructor defined for this object.
Not sure what I am doing wrong.
Thanks in advance
Neo
Lucian's suggestion is correct -- the AutoMapper.Extensions.Microsoft.DependencyInjection package is the way to go. Even if you don't want to use it, you'll have to do something similar.
I've had this very same problem and by using the extensions, you just modify the entrypoint from which you register AutoMapper and its configuration.
What the extensions do (source) is:
Initializes Automapper with the configuration provided
It scans for all classes you have that you could be implementing with dependency injection and registers them as transient, looking for implementations of the following:
IValueResolver
IMemberValueResolver
ITypeConverter
IMappingAction
The assemblies that it will scan actually depend on the parameters that you provide on the call.
If any of these can be actually instantiated, then they will be registered as transient implementation.
And just like that, AutoMapper will request instances of these to the service provider, which will resolve them, and to do that, it will also resolve any pending dependencies.
Note that this is actually very simple -- the most difficult part is scanning the right assemblies and registering the right classes. You can do it manually too, but these extensions already take care of it for you.
Mind you, even when reflection has been improved a lot, this process is relatively slow, so try not to abuse it too much (for instance, in tests).
Finally, if none of that works for you, remember that you need to setup AutoMapper to use the dependency injection resolver too:
automapperConfiguration.ConstructServicesUsing(serviceProvider.GetService);
I am new to Repository and DI and trying to implement in my MVC 5 project.
I implemented Constructor Injection where in my controller has a constructor like this:
IBook _ibook;
public Test(IBook ibook)
{
_ibook = ibook;
}
Without any DI library, it throws an error: There is no empty constructor.
To avoid this, I added one more constructor as below:
public Test ():this(new Book())
{
}
Since I am new to DI, I don't want to risk my project by using DI library which can later throw some error that I may not be able to resolve.
I want to know what issues I might encounter if I am not using DI library.
In case it is recommended, which DI library is good for beginners? I have seen few videos of NInject and Unity.
It is a good idea to delay any decision to use some kind of tool or library until the last responsible moment. With a good design you can add a DI library later on. This means that you practice Pure DI.
The preferred interception point in MVC is the IControllerFactory abstraction since it allows you to intercept the creation of MVC controllers, and doing so prevents you from having to implement a second constructor (which is an anti-pattern). Although it is possible to use IDependencyResolver, the use of that abstraction is much less convenient because it is also called by MVC to resolve things you are typically not interested in.
A custom IControllerFactory that will act as your Composition Root can be implemented as follows:
public sealed class CompositionRoot : DefaultControllerFactory
{
private static string connectionString =
ConfigurationManager.ConnectionStrings["app"].ConnectionString;
private static Func<BooksContext> bookContextProvider = GetCurrentBooksContext;
private static IBookRepository bookRepo = new BookRepository(bookContextProvider);
private static IOrderBookHandler orderBookHandler = new OrderBookHandler(bookRepo);
protected override IController GetControllerInstance(RequestContext _, Type type) {
// Unfortunately, because of MVC's design, controllers are not stateless, and
// you will have to create them per request.
if (type == typeof(OrderBookController))
return new HomeController(orderBookHandler);
if (type == typeof(BooksController))
return new BooksController(bookRepo);
// [other controllers here]
return base.GetControllerInstance(_, type);
}
private static BooksContext GetCurrentBooksContext() {
return GetRequestItem<BooksContext>(() => new BooksContext(connectionString));
}
private static T GetRequestItem<T>(Func<T> valueFactory) where T : class {
var context = HttpContext.Current;
if (context == null) throw new InvalidOperationException("No web request.");
var val = (T)context.Items[typeof(T).Name];
if (val == null) context.Items[typeof(T).Name] = val = valueFactory();
return val;
}
}
Your new controller factory can be hooked into MVC as follows:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start() {
ControllerBuilder.Current.SetControllerFactory(new CompositionRoot());
// the usual stuff here
}
}
When you practice Pure DI, you will typically see your Composition Root consist of a big list of if statements. One statement per root object in your application.
Starting off with Pure DI has some interesting advantages. The most prominent one is compile time support, because this is something you will lose immediately when you start using a DI library. Some libraries try minimize this loss by allowing you to verify your configuration in a way that the compiler would do; but this verification is done at runtime and the feedback cycle is never as short as that which the compiler can give you.
Please don't be tempted to simplify development by implementing some mechanism that allows creating types using reflection, because in doing so you are building your own DI library. There are many downsides to this, e.g. you lose compile time support while not getting back any of the benefits that an existing DI library can give you.
When your Composition Root is starting to get hard to maintain, that is the moment you should consider switching from Pure DI to a DI library.
Do note that in my example Composition Root, all application components (except for the controllers) are defined as singleton. Singleton means that the application will only have one instance of each component. This design needs your components to be stateless (and thus thread-safe), anything that has state (such as the BooksContext) should not be injected through the constructor. In the example I used a Func<T> as the provider of the BooksContext which is stored per request.
Making your object graphs singletons has many interesting advantages. For instance, it prevents you from making common configuration errors such as Captive Dependencies and it forces you into a more SOLID design. And besides, some DI libraries are very slow, and making everything a singleton might prevent performance problems when switching to a DI library later on. On the other hand, the downside of this design is that everybody on the team should understand that all components must be stateless. Storing state in components will cause needless grief and aggravation. My experience is that stateful components are much easier to detect than most DI configuration errors. I have also noticed that having singleton components is something that feels natural to most developers, especially those who aren't experienced with DI. For a detailed discussion on the two composition models to choose from and their downsides and advantages, take a look at this serie of blog posts.
Note that in the example I manually implemented a per-request lifestyle for the BooksContext. Although all DI libraries have out-of-the-box support for scoped lifestyles such as per-request lifestyles, I would argue against using those scoped lifestyles (except perhaps when the library guarantees to throw an exception instead of failing silently). Most libraries do not warn you when you resolve a scoped instance outside the context of an active scope (for instance resolving a per-request instance on a background thread). Some containers will return you a singleton instance, others return you a new instance each time you ask. This is really troublesome because it hides bugs and can cause you many hours trying to debug your application (I speak from experience here).
The simplest and sanest solution is to use Pure DI. With ASP.NET MVC, this is most easily done by deriving from DefaultControllerFactory and overriding GetControllerInstance:
protected override IController GetControllerInstance(
RequestContext requestContext, Type controllerType)
{
if (controllerType == typeof(Test))
return new Test(new Book());
return base.GetControllerInstance(requestContext, controllerType);
}
Then register your new Controller Factory in your Global.asax like this:
ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
Unfortunately, much documentation will tell you to use IDependencyResolver, or Bastard Injection to deal with Dependency Injection, but these will not make your code more maintainable.
There are lots of more details, including examples of how to properly use Dependency Injection with ASP.NET MVC, in my book.
If you're only interested in Dependency Injection to achieve some level of abstraction, you're definitely not required to use any IoC framework.
If you don't care about scope, lifetime and nested dependencies, you may end up with something as primitive as this:
internal class MyBasicResolver : IDependencyResolver
{
private readonly Dictionary<Type, Type> _services = new Dictionary<Type, Type>()
{
{ typeof(IBook), typeof(Book) }
// more services registrations
};
public object GetService(Type serviceType)
{
return _services.ContainsKey(serviceType) ? Activator.CreateInstance(_services[serviceType]) : null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
yield return GetService(serviceType);
}
}
Then register it as the current Dependency Resolver for MVC:
DependencyResolver.SetResolver(new MyBasicResolver());
See MSDN
Ninject and unity provide object container, which contains object wich you have register at startup of the application,
But why you need to use di, Di states that two objects should not depend upon its concreation it should depend upon its abstraction, so if suppose in futere you need to replace Book class to eBook, here both the class has same function but it has diffrunt concreation at that time you need to just your di configuration you dont need to recode the controller for eBook.
I am using unity di in my most projects I didt face any issue which I cant resolve its easy and make practice to use that, dont be afraid for that.
I'm trying to implement a role provider using a separate EF repository class, as an injectable dependency, to access my roles store. My problem is that the role provider is defined in configuration (web.config) and therefore is not instantiated via the Unity DI container. I haven't been able to find a way to either shift the configuration to code or get hold of the role provider after it's built to call container.BuildUP() on it. Any suggestions would be appreciated.
I think that my question's solution is fairly well covered here:
Property injection in custom membership provider using Castle
If I'd searched on MembershipProvider instead of RoleProvider probably would have found it the first time through.
Just to summarize my solution, the link lead me to the Common Service Locator library at codeplex.
It and the Unity adapter for it are included in the Nuget package for Unity 3. So I already had it.
I added one line to the end of the Compose() method of my CompositionRoot class:
var locator = new UnityServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => locator);
And I can now access the locator/container thru the static ServiceLocator class in the constructor of my RoleProvider:
public IAuthorizationManager Manager {get; set;}
public MyRoleProvider()
{
var locator = ServiceLocator.Current;
Manager = locator.GetInstance<IAuthorizationManager>();
}
(Of course, you need 'using' statements for Microsoft.Practices.ServiceLocation)
I'm trying to inject a repository to a custom membership provider with ninject in MVC 3.
In MembershipProvider I have tried the following:
[Inject]
public ICustomerRepository _customerRepository{ get; set; }
And
[Inject]
public TUMembershipProvider(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
In my ninject module i tried the following:
Bind<MembershipProvider>().ToConstant(Membership.Provider);
None of the above works.
When i use(in global.asa)
kernel.Inject(Membership.Provider);
together with
[Inject]
public ICustomerRepository _customerRepository{ get; set; }
it works, but i have no life cycle management and this will cause a "ISession is open" error from NHibernate, because the ISession is InRequestScope and the repository is not.
You could use the approach #Remo Gloor outlines in his blog post on provider injection. It involves 3 steps:
Add [Inject]s to any properties on your provider you need injected (although the pattern he shows -- creating a very simple class whose only function is to be a receptable for property injection and forwards any requests to a real class implemented using constructor injection -- is well worth following)
public class MyMembershipProvider : SqlMembershipProvider
{
[Inject]
public SpecialUserProvider SpecialUserProvider { get;set;}
...
Create an initializer wrapper that implements IHttpModule which pulls the provider in, triggering its creation:-
public class ProviderInitializationHttpModule : IHttpModule
{
public ProviderInitializationHttpModule(MembershipProvider membershipProvider)
{
}
...
Register the IHttpModule in your RegisterServices :-
kernel.Bind<IHttpModule>().To<ProviderInitializationHttpModule>();
there is no 4; Ninject does the rest - bootstrapping all registered IHttpModules including the one you added) during the startup sequence.
(Don't forget to read the comments on the blog post re lifetimes etc.)
Finally, if you're looking for something completely braindead direct that solves it neatly, try this #Remo Gloor answer instead
PS a great writeup on the whole mess is Provider is not a Pattern by #Mark Seemann. (and the oboligatory plug for his excellent book:- Dependency injection in .NET which will have you figuring this stuff out comfortably from first principles)
i had this problem
a custom membership, role and profile provider in another project from MVC using repository, when ever i call the provider the injected repository was null.
tried to call kernel.Inject(Membership.Provider); in the NinjectWebCommon method registerServices(IKernel kernel) but got the exception
The result is always null, because asp.net has it's own static property for membership.which is membership.provider. and this instance is not part of instance ninject management.
so use on PostApplicationStartMethod
here is the soloution by cipto add to NinjectWebCommon the attrbute and method :
[assembly: WebActivator.PreApplicationStartMethod(typeof(WebApp.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.PostApplicationStartMethod(typeof(WebApp.App_Start.NinjectWebCommon), "RegisterMembership")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(WebApp.App_Start.NinjectWebCommon), "Stop")]
public static void RegisterMembership()
{
bootstrapper.Kernel.Inject(Membership.Provider);
}
The problem is that the whole Membership infrastructure is a "native" .NET code (System.Web.Security) that does not know about MVC and about the DI container used by MVC.
The static call to Membership.Provider returns the membership provider based on the configuration, however, the specified provider type is instantiated with a simple Activator.CreateInstance call. Hence, the dependency injection has no chance to kick in and set your repository dependency on the result. If you explicitly setup the returned instance with Ninject it can work, because you explicitly gave Ninject the object to set the dependencies. Even in this case it can only work with property injection and not with constructor injection, because the instance is created by the membership configuration previously.
To summarize: you cannot easily inject dependencies into the membership provider because it is not resolved from a dependency injection container.
I think you have 2 possibilities:
You create a repository in the custom membership provider directly or you access it by some other means on demand (where the web context is already present).
You go one level higher and check the components that would use your membership provider and you try change there (to use a membership provider resolved from your DI container instead of the uninitialized Memership.Provider). If this "higher component" is the forms authentication, then this article might be of help (using dependency injection with IFormsAuthentication and IMembershipService): http://weblogs.asp.net/shijuvarghese/archive/2009/03/12/applying-dependency-injection-in-asp-net-mvc-nerddinner-com-application.aspx
Did you try resolving your repository "manually", like in this answer:
Ninject : Resolving an object by type _and_ registration name/identifier
?
I am in the process of creating a custom membership provider for an ASP.Net MVC website. The provider is being created as a separate class as part of a bigger library. There is a need for the back-end data store to be flexible as it could be an Xml File or SQL database. My initial thought was to create an interface for the data store and inject this into provider using dependency injection.
The end result is required is that a developer can inherit the data store interface and provide the required methods to update the data, which will then be used by the custom membership providers.
However through my own lack of skill I can't figure out how to inject the class into the membership provider when adding it to the website? What needs to be done to link the data store to the provider? What would be the simplest way to enable this in the website?
If you are configuring the custom membership providers via the <membership> element in the Web.config file, then I can see the issues you will have with dependency injection.
The providers are constructed and managed by the framework, and there is no opportunity for you to intercept that construction to provide additional dependency injection for the IDataStore interface.
If my assumption is correct, then what you can do is override the Initialize() method in your custom provider, and do the dependency injection there. You can have a custom name/value setting in the provider configuration which points to a type that implements IDataStore, which is passed as part of a dictionary to the Initialize() method.
Then, you activate an instance of the data store type and set it on the appropriate property:
public class MyMembershipProvider : MembershipProvider
{
public IDataStore DataStore
{
get;
set;
}
public override Initialize(string name, NameValueCollection config)
{
var dataStoreType = config["dataStoreProvider"];
if (!String.IsNullOrEmpty(dataStoreType))
{
var type = Type.GetType(dataStoreType);
DataStore = (IDataStore) Activator.CreateInstance(type);
}
}
}
Initialize() will be called by the framework after it constructs an instance of your provider, so that is the perfect place to do any additional setup work such as this.
For testing scenarios, you just set the data store property on the provider instance itself, as you will be constructing it directly in your tests.
Isn't this better? I use it with MVC3 and ninject. It's enough to add a property to your custom membership provider class. Remember to add "using System.Web.Mvc;" on top.
public IRepository Repository
{
get
{
return DependencyResolver.Current.GetService<IRepository>();
}
}
The simplest way to do dependency injection that I've seen (and actually the only one I've used so far...) is to have a constructor of your dependent class take the interface as a parameter, and assign it to a private field. If you want, you can also add a "default" constructor, which chains to the first one with a default value.
Simplified, it would look something like this:
public class DependentClass
{
private IDataStore _store;
// Use this constructor when you want strict control of the implementation
public DependentClass(IDataStore store)
{
this._store = store;
}
// Use this constructor when you don't want to create an IDataStore instance
// manually every time you create a DependentClass instance
public DependentClass() : this(new DefaultDataStore()) { }
}
The concept is called "Constructor chaining", and there's a lot of articles on the web on how to do it. I find this tutorial very explanatory of the DI pattern.