Ninject EventBroker automatic registration - events

Is it possible to get all injected items to automatically be registered with the EventBroker? The alternate is to inject the IEventBroker in each type, but this is error prone.

You cannot register them when an object is injected. But you can register an object when it is created by using .RegisterOnGlobalEventBroker(); or/and RegisterOnEventBroker("MyGlobalEventBroker") from https://github.com/ninject/ninject.extensions.bbveventbroker

Related

Register and Resolve DI containers in Prism 7 - Xamarin Forms

I'm using prism 7 for my new xamarin forms application.I have gone through this document.
I have couple of questions:
There are few DI interfaces I register after the app starts. We can use IContainerRegistry in app.xaml.cs to register but if we want to register or resolve in other pages, is there any way to get do it other that saving the IContainerRegistry and IContainerRegistry instance from app.xaml.cs and using it where ever we want?
To register a type the syntax is :
ContainerRegistry.RegisterInstance<ITextService>(new TextService());
But how can we register a singleton?
I saw few examples but I did not really understand how to do it? can anyone please show an example?
UPDATE:
To register a singleton,
The syntax seems like
containerRegistry.RegisterSingleton<ILoggerFacade, EmptyLogger>(); but if we just pass the type without creating an instance ( in this case, the instance of EmptyLogger), how can we use properly register them?
To register a type the syntax is: ContainerRegistry.RegisterInstance<ITextService>(new TextService());
this registers an instance not a type, btw, to register a type do ContainerRegistry.Register<IAnInterface, SomeImplementation>();
But how can we register a singleton?
ContainerRegistry.RegisterSingleton<ITextService, TextService>(); does this, and btw, an instance is a singleton by nature (because the di container always has to inject the one instance you registered as it cannot create new instances on its own)
is there any way to get do it other that saving the IContainerRegistry and IContainerRegistry instance from app.xaml.cs and using it where ever we want?
I recommend registering everything in one place rather than scattering registrations all over the project. But if you're determined, you can have IContainerRegistry injected anywhere and register your stuff.

How can I get access to the HttpRequestMessage in Ninject?

I currently have filters and message handlers that add values to the request properties (i.e. via HttpRequestMessage.Properties.Add). I'd like to use these values in constructor injection of my controllers using Ninject. How can I access the current request object using Ninject?
In ASP.NET MVC, I was able to use HttpContext.Current in a Kernel.Bind<>().ToMethod() anonymous function. Web API doesn't have a static state object and I'd like to avoid creating one.

Removing an added provider in Jersey

I am using com.yammer.dropwizard.config.Environment addProvider method to register providers in Jersey.I have a custom provider too which does a task similar to Dropwizards own MessageBodyWriterProvider.
Jersey seems to select the inbuilt MessageBodyWriter instead of my custom one.So I figured that if I remove the inbuild provider which is registered and register my own it will work properly.
Is there a way to remove the already added provider with the class name or other way?
environment.getJerseyResourceConfig().getSingletons()
returns a mutable Set<Object> of all the resources and providers registered with Jersey. A simple iteration over this with an instanceOf check should be enough.
The related method getProviderSingletons won't work because it is returning a new set. And removing from that set won't remove from the original.

Errors object required in invoking Spring validation

I am working on a application using spring. i want to use spring validation framework for validating different domain/model objects from the service layer which has the validator injected. I am planning to use ValidationUtils to invoke validator, but i am not sure what implementation of errors i need to pass to the invokeValidator method.
Signature in ValidationUtils:
invokeValidator(Validator validator, Object obj, Errors errors)
Will it be right to use BeanPropertyBindingResult.
BeanPropertyBindingResult result = new BeanPropertyBindingResult(javaProduct, "javaProduct");
Yes ofcourse. You can pass object of BeanPropertyBindingResult object to the Errors.
It is implements the interface Errors.
Hope this helps you. Cheers.

MVC3 Action Filter Using Database (EF 4.1 DBContext, Ninject)

I'm trying to setup an 'Authorization' Filter on an Action, creating my own ActionFilterAttribute where I do a database lookup to determine if a user has access to a certain resource.
On my class inheriting from ActionFilterAttribute, I have created an Injected(Ninject) property to hold the service that I am using for the database access. I have a parameterless constructor so that I can use this as an attribute on my actions. In the 'OnActionExecuting' Method, I am able to gain access to the Injected property (it's not null), but the base DBCotext that it is using is closed.
This working fine, up until the RTM of MVC3, where the Release Notes stated:
Breaking Changes:
In previous versions of ASP.NET MVC, action filters are create per
request except in a few cases. This
behavior was never a guaranteed
behavior but merely an implementation
detail and the contract for filters
was to consider them stateless. In
ASP.NET MVC 3, filters are cached more
aggressively. Therefore, any custom
action filters which improperly store
instance state might be broken.
The first time I use this filter, it works as expected, but if I refresh the page or another user access this filter, I get the error:
The operation cannot be completed
because the DbContext has been
disposed.
which is what I guess I should expect given the breaking changes notes.
My question is this, what would be the preferred/recommended way of accomplishing what I need to do? Should this be in an ActionFilterAttribute, or should this 'authorization' be done somewhere else?
I'd do authentication in Application_AuthenticateRequest and authorization in your attribute using Thread.CurrentPrincipal, but your method should work too. You just need to count with fact that DbContext will be different for each request but your attribute won't. Something like this should do the trick (I'm assuming you are using DependencyResolver):
public class MyMightyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var context = (DbContext)DependencyResolver.Current.GetService(typeof(DbContext))
// authenticate, authorize, whatever
base.OnActionExecuting(filterContext);
}
}
I have been battling with this for a while and finally solved my problem. So here is my solution in the hope it may help someone else.
The setup:
1. I have an MVC3 project, a custom action filter that accesses the db using EF5 via a business service.
2. I use Unity and unity.MVC to resolve my dependencies on a per request basis.
3. I use property injection into my custom Action filter, as it has a parameterless constructor.
The result.
Dependency injection works correctly for all the services used by actions, my EF DbContext is correctly disposed of at the end of each request.
The Problem
Although my property dependency is resolved in my custom action filter, it contains a stale instance of my DbContext (e.g. it seems to have been cached from the previous request)
As mentioned in previous posts, MVC3 is more aggressive with filter caching and the state of a filter cannot be relied on. So the suggestion was to resolve the dependency in the OnActionExecuting method. So I removed my injected property and did just that called resolve on my unity container. However I still got a stale version of the DbContext. Any changes in the DB were correctly queried in my main actions, but the custom action filter didn’t pick them up.
The solution.
Unity.MVC Manages per-request lifetime by using child containers and disposing these at the end of each request. By resolving my dependency’s in the action filter from my unity container I was resolving from the parent container which is not disposed of on each request.
So rather than
IoC.Instance.CurrentContainer.Resolve<IService>();
I used this to obtain an instance of the child container rather than parent.
var childContainer = HttpContext.Current.Items["perRequestContainer"] as IUnityContainer;
var service = childContainer.Resolve<IServcie>();
I'm sure there must be a clean way to achive the same result, so please add suggestions.
Ok slight refinement to allow my unit test to inject a mock of the service.
1. remove the dependency resolve from the the OnActionexecuting and add two constructors.
public MyCustomActionfilter() : this(((IUnityContainer)HttpContext.Current.Items["perRequestContainer"].Resolve<IService>())
and
public MyCustomActionfilter(IService service)
{
this.service = service;
}
Now the constructor resolves your service and stores it as a private readonly. This can now be consumed in your OnActionExecutng function. Unit tests can now call the second constructor and inject a mock.

Resources