Ninject InRequest Scope Losing Binding - asp.net-mvc-4

I'm having a frustrating issue with Ninject and MVC 4.
Here is the code block:
Kernel.Bind<IUserInfo>().To<UserInfo().InRequestScope();
var userInfo = Kernel.Get<IUserInfo>();
Most of the time, this is fine, and I have a user info. Sometimes, though, I get the following error:
Error activating IUserInfo
No matching bindings are available, and the Type is not self-bindable.
Activation path:
1) Request for IUserInfo
Suggestions:
1) Ensure that you have defined a binding for IUserInfo.
2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
3) Ensure you have not accidentally created more than one kernel.
4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.\r\n 5) If you are using automatic module loading, ensure the search path and filters are correct.
I've pared down everything I cant think to, and am at a loss. I don't know why this would fail intermittently. Based on my admittedly limited knowledge of Ninject, there should be no way for the binding to be missing.
I see a lot of references to using the Ninject MVC Nuget packages, but the app as I inherited it does not use those, it initializes Ninject using an ActionFilter. Is this pattern just broken at its core, and somehow interfering with proper binding?
Help?

Take a look at the BindFilter option
https://github.com/ninject/ninject.web.mvc/wiki/Filter-configurations
There is some sort of caching issue I believe, that makes filters behave differently to controllers. This means that the binding can fail, usually under heavy load, but unpredicatably.

It turns out that newer versions of Ninject need more setup for InRequestScope to work. By removing Ninject entirely, and readding references to Ninject, Ninject.Web.Common, and Ninject.Web.MVC, it added the Ninject.Web.Common.cs file that was neccessary for InRequestScope to work.
Previously, it was actually binding InTransientScope, which meant it would get garbage collected, which is non-deterministic, which explains my intermittent issues. I wish it would have thrown exceptions when i tried to bind InRequestScope, but c'est la vie.

Related

Does Binding Order Matter When Using WhenInjectedExactlyInto and a Default Binding?

With multiple Ninject modules, I end up having a binding order for a particular interface which looks like this:
Kernel.Bind<ILogger>().To<Logger>().WhenInjectedExactlyInto(typeof(TroubleshootingLogger), typeof(RegularAndStashLogger), typeof(LogStashLogger), typeof(KafkaSendClient));
Kernel.Bind<ILogger>().To<TroubleshootingLogger>();
Kernel.Bind<ILogger>().To<RegularAndStashLogger>().WhenInjectedExactlyInto<ProcessConfiguration>();
My question is if, when I call the Kernel for an instance of ProcessConfiguration, will it inject TroubleshootingLogger (the default bind), or RegularAndStashLogger (the exact bind)?
I went ahead and built a small test program to determine this myself (I acknowledge I should have done this first).
As it turns out, Ninject does appear to check all "WhenInjectedExactlyInto" bindings before falling back to a default binding.
The program (which depends on Ninject to run, duh): pastebin.com/9Kpsb25h

How to wire up WCF Service Application, Unity and AutoMapper

I have been playing around the last couple of days with different solutions for mapping DTO's to entities for a VS2013, EF6, WCF Service App project.
It is a fairly large project that is currently undergoing a major refactoring to bring the legacy code under test (as well as port the ORM from OpenAccess to EF6).
To be honest I had never used AutoMapper before but what I saw I really liked so I set out to test it out in a demo app and to be honest I am a bit ashamed that I have been unable to achieve a working solution after hours of tinkering and Googling. Here is a breakdown of the project:
WCF Service Application template based project (.svc file w/code behind).
Using Unity 3.x for my IoC container and thus creating my own ServiceHostFactory inheriting from UnityServiceHostFactory.
Using current AutoMapper nuget package.
DTO's and DAL are in two separate libraries as expected, both of which are referenced by the service app project.
My goal is simple (I think): Wire up and create all of my maps in my composition root and inject the necessary objects (using my DI container) into the class that has domain knowledge of the DTO's and a reference to my DAL library. Anyone that needs a transformation would therefore only need to reference the transformation library.
The problem: Well, there are a couple of them...
1) I cannot find a working example of AutoMapper in Unity anywhere. The code snippet that is referenced many times across the web for registering AutoMapper in Unity (see below) references a Configuration class that doesn't seem to exist anymore and I cannot find any documentation on its deprecation:
container.RegisterType<AutoMapper.Configuration, AutoMapper.Configuration>(new PerThreadLifetimeManager(), new InjectionConstructor(typeof(ITypeMapFactory),
AutoMapper.Mappers.MapperRegistry.AllMappers())).RegisterType<ITypeMapFactory,
TypeMapFactoy>().RegisterType<IConfiguration, AutoMapper.Configuration>().RegisterType<IConfigurationProvider,
AutoMapper.Configuration>().RegisterType<IMappingEngine, MappingEngine>();
2) Where to create the maps themselves... I would assuming that I could perform this operation right in my ServiceHostFactory but is that the correct place? There is a Bootstrapper project out there but I have not gone down that road (yet) and would like to avoid it if possible.
3) Other than the obviously necessary reference to AutoMapper in the DTO lib, what would I be injecting into the instantition, the configuration object (assuming IConfiguration or IConfigurationProvider) and which class I am injecting into the constructor of the WCF service to gain access to the necessary object.
I know #3 is a little vague but since I cannot get AutoMapper bound in my Unity container, I cannot test/trial/error to figure out the other issues.
Any pointers would be greatly appreciated.
UPDATE
So I now have a working solution that is testing correctly but would still like to get confirmation that I am following any established best practices.
First off, the Unity container registration for AutoMapper (as of 11/13/2013) v3.x looks like this:
container
.RegisterType<ConfigurationStore, ConfigurationStore>
(
new ContainerControlledLifetimeManager()
, new InjectionConstructor(typeof(ITypeMapFactory)
, MapperRegistry.AllMappers())
)
.RegisterType<IConfigurationProvider, ConfigurationStore>()
.RegisterType<IConfiguration, ConfigurationStore>()
.RegisterType<IMappingEngine, MappingEngine>()
.RegisterType<ITypeMapFactory, TypeMapFactory>();
Right after all of my container registrations, I created and am calling a RegisterMaps() method inside of ConfigureContainer(). I created a test mapping that does both an auto mapping for like named properties as well as a custom mapping. I did this in my demo app for two reasons primarily:
I don't yet know AutoMapper in a WCF app hosted in IIS and injected with Unity well enough to fully understand its behavior. I do not seem to have to inject any kind of configuration object into my library that does the transformations and I am still reading through the source to understand its implementation.
As I understand it, there is a caching mechanism at play here and that if a mapping is not found in cache that it will create it on the fly. While this is great in theory, the only way I could then test my mappings that were occurring in my composition root was to do some sort of custom mapping and then call Mapper.Map in the library that performs mapping and returns the DTO.
All of that blathering aside, here is what I was able to accomplish.
WCF Service App (composition root) injects all of the necessary objects including my DtoConversionMapper instance.
The project is made up of the WCF Service App (comp root), DtoLib, DalLib, ContractsLib (interfaces).
In my ServiceFactoryHost I am able to create mappings, including custom mappings (i.e. map unlike named properties between my DTO and EF 6 entity).
The DtoConversionMapper class lives in the DtoLib library and looks like this: IExampleDto GetExampleDto(ExampleEntity entity);
Any library with a reference to the DtoLib can convert back and forth, including the Service App where the vast majority of these calls will take place.
Any guiding advice would be greatly appreciated but I do have a working demo now that I can test things out with while I work through this large refactoring.
Final Update
I changed the demo project just a little by adding another library (MappingLib) and moved all of my DTO conversions and mappings to it in a static method. While I still call the static method in my composition root after the Unity container is initialized, this gives me the added flexibility of being able to call that same map creation method in my NUnit unit test libraries, effectively eliminating any duplication of code surrounding auto mapper and makes it very testable.

Disable implicit binding/injection of non explicitly bound classes in Ninject 2+

If you request an unbound object from NInject, then the default behaviour is (if a suitable constructor is available) appears to be to create an instance of the appropriate object.
I'd like to disable this behaviour (I had a difficult to debug issue because something was auto-bound instead of picking up my custom binding in a module). This question hints that it is possible, but I'm unable to find the answer from the NInject wiki.
Remove the SelfBindingResolver from the kernel components after creation:
kernel.Components.RemoveAll<IMissingBindingResolver>();
kernel.Components.Add<IMissingBindingResolver, DefaultValueBindingResolver>();
The following is a better, more direct way of removing the SelfBindingResolver, without assuming that the DefaultValueBindingResolver is the only other IMissingBindingResolver component:
kernel.Components.Remove<IMissingBindingResolver, SelfBindingResolver>();
It's possible the Remove<T, TImplementation>() method was only added in a recent version of Ninject, but this works for me using Ninject 3.2.2.0.

System.Collections.ObjectModel.ObservableCollection only partially implemented in Monotouch?

I'm consuming WCF services using the Silverlight 3 stubs and one parameter I need is a System.Collections.ObjectModel.ObservableCollection.
However the following code is throwing a NotImplementedException:
ItemType[] aItemTypes = ...;
ObservableCollection<ItemType> aTypes = null;
if(aItemTypes != null)
{
aTypes = new ObservableCollection<ItemType> (aItemTypes);
}
If I use a foreach loop to add all entries manually instead of using the constructor that takes an enumerable, it works. Is there a reason why the constructor is missing or was it just forgotten?
Is there a reason why the constructor is missing or was it just forgotten?
This sometimes occurs on Mono base class library source code when someone implement a type but does not need everything inside it. In such cases it's better to add stubs for the missing code since this:
allow compilation of existing code;
it avoid MissingMethodException at runtime, a NotImplementedException is easier to diagnose;
allow Mono's tooling, e.g. MoMA and Gendarme, to report the NotImplementedException on existing .NET code.
In this specific case I suspect that more tests were needed to see if the items being copied needed to trigger events (whgen adding them) or not.
The good news is that this method is implemented in Mono's GIT master. I'll look into backporting this into mono-2-10 branch so MonoTouch will get it in future releases.

Ninject Interceptors class with parameters

Simple question... I want to use Ninject Interceptors to take care of my NFRs, however alot of my classes require arguments in the constructors. I read that they are looking at allowing constructors with arguments but currently I get an error:
Can not instantiate proxy of class: myClass
Could not find a parameterless constructor.
Parameter name: constructorArguments
I am using version 2.2.1 I think, noticed there is a tagged 2.3 version on the extensions site, but will any of this solve my problems? if not is there any way around this?
2.3 adds support for Interface proxies. This means it will solve the problem for all types that are resolved by interface. It's also planned to add support for classes without default constructor.
But be aware that 2.3 is work in progress. While there aren't any known new problems it is not tested yet against real applications as 2.2 is and interface changes of new stuff can still change. Also InRequestScope support for XML and Conventions has temporarily been disabled.