Inject IAuthorizationFilter using Unity - asp.net-mvc

I am trying to inject IAuthorizationFilter with SecurityAuthorizationFilter using Unity through configuration. I get an exception The type name or alias IAuthorizationFilter could not be resolved. Please check your configuration file and verify this type name. I checked the types and all of them looks good. Please somebody direct me how can I typically inject the action filters. Thanks in advance
My configuration as follows
<typeAlias alias="IAuthorizationFilter" type="System.Web.Mvc.IAuthorizationFilter, System.Web.Mvc"/>
<typeAlias alias="SecurityAuthorizationFilter" type="JQS.Infrastructure.Security.Filters.SecurityAuthorizationFilter, JQS.Infrastructure.Security"/>
<register type="IAuthorizationFilter" mapTo="SecurityAuthorizationFilter"/>
-George

Try to write full assembly name in type attribute for IAuthorizationFilter alias ( I mean version, culture, public token )

Related

Ninject: Bind ServiceHost instance for use with WCF duplex service

I'm working on a WCF service that uses a duplex channel to allow the service to call back to the client to relay an event raised by a component in the service layer. The proxy class is defined and constructed like this:
public class EvsMembershipProxy : DuplexClientBase<IMembershipProviderCallback>, IEvsMembershipProvider
{
public EvsMembershipProxy(InstanceContext callbackInstance): base(callbackInstance)
{
}
}
I need to get an instance of this class in a class that is configured using the ASP.NET membership system, so I bind it like this:
_ninjectKernal.Bind<IEvsMembershipProvider>().To<EvsMembershipProxy>();
and I inject it like this:
public class EvsMembershipProvider : MembershipProvider, IMembershipProviderCallback
{
#region "Dependencies"
[Inject]
public IEvsMembershipProvider MembershipProvider { get; set; }
#endregion
}
The configured membership provider is injected by Ninject like this:
_ninjectKernal.Inject(System.Web.Security.Membership.Provider);
_ninjectKernal.Inject(System.Web.Security.Roles.Provider);
I have tested the injection pattern with the WCF service layer without the duplex service and it works correctly. However, when I include the duplex service, Ninject fails during binding with the following error:
Error activating ServiceHostBase
No matching bindings are available, and the type is not self-bindable.
Activation path:
4) Injection of dependency ServiceHostBase into parameter host of constructor of type InstanceContext
3) Injection of dependency InstanceContext into parameter callbackInstance of constructor of type EvsMembershipProxy
2) Injection of dependency IEvsMembershipProvider into property MembershipProvider of type EvsMembershipProvider
1) Request for EvsMembershipProvider
Suggestions:
1) Ensure that you have defined a binding for ServiceHostBase.
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.
5) If you are using automatic module loading, ensure the search path and filters are correct.
So it looks as though I will need a binding for the ServiceHostBase class used in the EvsMembershipProxy constructor to resolve this issue. However, I don't know how to configure it. My best attempt to resolve the ServiceHostBase binding so far has been:
_ninjectKernal.Bind<ServiceHostBase>().ToMethod(c => OperationContext.Current.Host);
However this fails with a null reference exception during binding.
How do I bind the ServiceHostBase type so that this injection works?
** EDIT: simplified the original code to remove some of the EvsMembershipProxy constructor arguments which could be supplied by WCF configuration **
Discovered I could configure it like this.
_ninjectKernal.Bind<IEvsMembershipProvider>()
.To<EvsMembershipProxy()
.WithConstructorArgument("callbackInstance", Membership.Provider);
The configured membership provider implements the IMembershipProviderCallback interface and receives the callback from the service.

NPoco StructureMap.MVC4 Constructor Injection

I have an MVC4 application using StructureMap.MVC4. Here's a fragment of IoC.cs
ObjectFactory.Initialize(x =>{
x.Scan(scan =>{
scan.TheCallingAssembly();
scan.WithDefaultConventions();});
x.For<IDbContext>().Use<EfDbContext>().Ctor<string>("connectionStringName").Is("DefaultDb");
x.For<IDatabase>().Use<Database>().Ctor<string>("connectionStringName").Is("DefaultDb");
x.For<IActionInvoker>().Use<InjectingActionInvoker>();
x.SetAllProperties(c=>c.OfType<IDbContext>());
... ...
DbContext injection works fine, so does the setter injection for ActionFilters, as well as all Service:IService using default convention. But I got the following error trying to inject IDatabase:
Could not find a constructor parameter or property for NPoco.Database, NPoco, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null named connectionStringName Parameter name: name
If I change it to
x.For<IDatabase>().Use(new Database("DefaultDb"));
It works. Any ideas why? I wonder if by using New, it will end up a different instance of IDatabase, especially when mixing with the IDbContext instance. Thanks.
Seems related to StructureMap can't decide the default constructor when there are multiples with similar constructor parameters. In this case, it has
Database(string connectionStringName)
Database(string connectionStringName, string Provider)
....
Looks like this is slight better syntax?
x.For<IDatabase>().Use(() => new Database("DefaultDb"));

Injecting EJB in struts2 action?

Am using struts2 , EJB 3.0 ...
My requirement is to call the EJB layer from struts2 action class .
I hope there are two ways in achieving this :
1.Using #EJB annotation in Action class
2.Using JNDI look up
I tried both ,
but the problem with JNDI lookup is , eventhough am using correct naming , am getting NameNotFoundException . So the ultimately , my team moved to other method which is using #EJB annotation .
But when am using #EJB annotation am getting null out of it , I think its not injected :
am getting the NullPointerException
code :
#EJB(mappedName="BeanLocal/local")
BeanLocal bean ;
Can any one suggest me what i have to do further ...
Also if there is anylink in SOF , please do refer me as i found nothing related to this
You can't use the traditional dependency injection in Struts 2 action classes because actions aren't managed. However there is a way to achieve this by using the CDI plugin or Guice.
You can also use JNDI look up but the syntax depends on your server. Your best option is to check the documentation according to what you have (JBoss 7.1, Glassfish...)
I had this same problem and here is how I solved it.
As Shinosha said, the #EJB annotation will not work since the action classes are managed by the Struts container.
In order to use JNDI lookup, I had to make the bean #Remote and specify a mappedName. Then the code is as follows (it depends on the server your are using, in my case Weblogic):
Context ctx = new InitialContext();
MyBean bean= (MyBean) ctx.lookup("MyBeanMappedName#myapp.MyBean");
The lookup string should be the fully qualified name of the bean.
I wrote following interceptors to solve this issue. Have a look and share any feedback you may have :
http://gauravwrites.blogspot.com/2014/11/ejb-injection-in-struts2-interceptor.html

Passing constructor arguments to OutputCacheProvider

I have implemented a custom OutputCacheProvider
public class MongoDBCacheProvider : OutputCacheProvider, IDisposable { ... }
The cacheprovider is registered like so:
<outputCache defaultProvider="MongoDBCacheProvider" enableOutputCache="true" >
<providers>
<add name="MongoDBCacheProvider" type="Mynamespace.Core.Caching.MongoDBCacheProvider, Mynamespace.Core" />
</providers>
</outputCache>
I need to pass some arguments to the constructor. I want to use Ninject to bind my cache provider.
this.Bind<System.Web.Caching.OutputCacheProvider>()
.To<Core.Caching.MongoDBCacheProvider>()
.WithConstructorArgument("databaseName", dbName);
More arguments have to be passed, but this is just an example. I'm sure simple solutions exist to somehow get that string there, but i would prefer to use Ninject like i use for all other classes.
This fails with the message: "No parameterless constructor defined for this object." The following binding doesn't work either.
this.Bind<Core.Caching.MongoDBCacheProvider>().ToSelf()
.InSingletonScope()
.WithConstructorArgument("databaseName", dbName);
I have verified that the binding runs before the error occurs. ASP .NET somehow bypasses the ninject bindings.
There doesn't seem to be any way to plug in a factory for it either.
Does anybody know how i can pass constructor arguments to a derived OutputCacheProvider?
Thank you.
You should be able to Inject into the object early in your web app life cycle by causing it to be injected during app startup.
NB you will have to use Property Setter Injection in preference to Constructor Injection, as there is likely no way to get the Cache Provider Provider to give you control of the instance creation.
See this blog post by #Remo Gloor

Authorization and Windsor

I'm trying to implement my custom authorize attribute like:
public class MyCustomAuth : AuthorizeAttribute
{
private readonly IUserService _userService;
public MyCustomAuth(IUserService userService)
{
_userService= userService;
}
... continued
}
I am using Castle Windsor for automatically resolve the dependency.
When I try to use it as an attribute of an action method obviously I am asked to pass the parameter or I need to have a parameter-less constructor that should resolve in some way it's dependency.
I tried to inject the dependency with a property but Windsor is not injecting it.
The only option I see now would be to instantiate manually the concrete object dependency loosing the benefit of Windsor.
How would you solve this problem?
You cannot use DI with attributes - they're metadata;
public class MyCustomAuth : AuthorizeAttribute
{
public void OnAuthorization(...)
{
IUserService userService = ServiceLocator.Current.GetInstance<IUserService>();
}
}
Learn about Windsor/ServiceLocator here.
See similar question here.
You can use a custom ControllerActionInvoker and inject property dependencies (you can't do constructor injection because the framework handles instantiation of attributes). You can see a blog post I just did on this technique.
You did not supply any castle code or configuration examples. Therefore, I am assuming you are new to castle and unfimilar with the registration process.
First of all, any object you want to act upon must come from Castle Windsor via a registered type. With that said, you are going down the wrong path by trying to use castle windsor with attributes - because attributes are not referenced in code, but instead are reflected upon. Therefore, there is not a place for IoC (Castle Windsor in this case) to create the object.
I say this, because what you are trying to accomplish has already been done via different means. First of all, put your dependency injection on your controllers.
public class PostController
{
private IUserService _userService;
public PostController (IUserService userService)
{
_userService = userService;
}
// other logic
}
For Castle to work, you have register all types. So, you have to register IUserService, and what services implement that interface, within Castle Windsor. You can do this via a manual process in your global.asax with container.AddComponentWithLifeStyle; or the more preferred method is to use a configuration file.
Using a configuration file, your IUserService would look something like this:
<?xml version="1.0" encoding="utf-8" ?>
<castle>
<components>
<!--lifestyle="singleton|thread|transient|pooled|webrequest|custom"-->
<component
id="UserService"
service="MyMvcProject.IUserService, MyMvcProject"
type="MyMvcProject.UserService, MyMvcProject"
lifestyle="transient">
</component>
</components>
</castle>
MyMvcProject is the name of your project and make sure to use the exact namespace and fully qualified name of the interface, and type. Please give code samples of your actual namespaces, else we cannot help you any further.
Before that will work, you will need to modify your app.config or web.config to register the searchGroup for Castle Windsor:
<configSections>
<section name="castle"
type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
</configSections>
<castle configSource="castle.config"/>
Now that you are all registered and setup, it is time to tell your MVC application to "Use Castle Windsor to create each instance of my Controllers." Doing this means that Castle Windsor, being an Inversion-of-Control (aka IoC) container, will inspect the dependencies of your controller and see that it depends on IUserService and implement an instance of UserService. Castle will look into its configuration of registered types and see that you have registered a service for IUserService. And, it will see in your configuration file that you want to implement the concrete class of UserService that implements IUserService. So, the IoC container will return UserService when a dependency on IUserService is requested.
But before that can happen, you have to tell your MVC application to use your configuired IoC container. You do this by registering a new ControllerFactory. To do that, see my answer over at this question:
Why is Castle Windsor trying to resolve my 'Content' and 'Scripts' folder as a controller?
And notice the global.asax part of how to register that code. It works quite well!
Now, when all of that is said and done, you want to authorize a user. Use the normal [Authorize] that implements Forms Authentication, and use your _userService to grab any user details of the signed in user.

Resources