Cannot resolve the controller - asp.net

Previously I was not using an interface for my generic repository. When I extracted the interface from my generic repository, I added two constructors: a parameterless and a parameterized constructors I am getting the following error:
{"Resolution of the dependency failed, type = \"NascoBenefitBuilder.Controllers.ODSController\", name = \"(none)\".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, ControllerLib.Models.Generic.IGenericRepository, is an interface and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was:
Resolving NascoBenefitBuilder.Controllers.ODSController,(none)
Resolving parameter \"repo\" of constructor NascoBenefitBuilder.Controllers.ODSController(ControllerLib.Models.Generic.IGenericRepository repo)
Resolving ControllerLib.Models.Generic.IGenericRepository,(none)"}
My Controller at the beginning:
public class ODSController : ControllerBase
{
IGenericRepository _generic = new GenericRepository();
}
After extracting the interface and use it in controller:
public class ODSController : ControllerBase
{
IGenericRepository _generic;
public ODSController() : this(new GenericRepository())
{
}
public ODSController(IGenericRepository repo)
{
_generic = repo;
}
}
When I use parameterized constructor it is throwing error mentioned above.
Can anyone help me to overcome this problem?

You no longer need the default constructor:
public class ODSController : ControllerBase
{
private readonly IGenericRepository _repository;
public ODSController(IGenericRepository repository)
{
_repository = repository;
}
}
And then make sure you've properly configured your Unity container:
IUnityContainer container = new UnityContainer()
.RegisterType<IGenericRepository, GenericRepository>();
And that you are using the Unity controller factory in Application_Start:
ControllerBuilder.Current.SetControllerFactory(typeof(UnityControllerFactory));

Related

Getting IllegalArgumentException while registering Oracle Service in Corda

I have created Oracle service with #CordaService annotation
I am getting Exception while installing Corda Service.
It will not get defined service type, got size 0 in List object in first argument of constructor.
public NumberVerifierOracle(PluginServiceHub services){
this(services.getMyInfo().serviceIdentities(NumberVerifierOracleType.getNumberVerifierOracleType().getServiceType()).get(0),services);
}
The defined service type is:
public class NumberVerifierOracleType {
private static ServiceType serviceType;
private static NumberVerifierOracleType numberVerifierOracleType = new NumberVerifierOracleType();
private NumberVerifierOracleType(){
serviceType = ServiceType.Companion.getServiceType("com.template.oracle.service","numberVerifierService_NumberVerifierOracle");
}
public static NumberVerifierOracleType getNumberVerifierOracleType() {
return numberVerifierOracleType;
}
public ServiceType getServiceType() {
return serviceType;
}
}
The Package hierarchy is:
com.template.oracle.service.NumberVerifierOracle class
I have resolved this error by making service with Public modifier.
Like this:
public static ServiceType type;
static{
type= NumberVerifierOracleType.getNumberVerifierOracleType().getServiceType();
}
It will not work if we have private modifier and use directly getter method.

strucutreMap Dependency injection is not working

In my application i configured structuremap like
public class DefaultRegistry : Registry {
#region Constructors and Destructors
public DefaultRegistry() {
Scan(
scan => {
scan.Assembly("Eterp.Data.ErpCore");
scan.Assembly("Eterp.Data.Seed");
scan.Assembly("Eterp.Application.ErpCore");
scan.TheCallingAssembly();
scan.WithDefaultConventions();
});
ForConcreteType<AclAuthorizationManager>().Configure.Ctor<IResourceOperationAppService>()
}
#endregion
}
And i have class
public class AclAuthorizationManager : ClaimsAuthorizationManager
{
private readonly IResourceOperationAppService _resourceOperationAppService;
public AclAuthorizationManager(IResourceOperationAppService resourceOperationAppService)
{
_resourceOperationAppService = resourceOperationAppService;
}
public override bool CheckAccess(AuthorizationContext context)
{
var isCurrentUserAuthorized = context.Principal.Identity.IsAuthenticated;
return isCurrentUserAuthorized && _resourceOperationAppService.CanAccessResource(context.Action.FirstOrDefault().Value, context.Principal.Claims);
}
}
This class is custom claim authorization class using in my application, but when i exceuting the application,i am getting an error which related to lack of parameter required by the constructor, ( This class has constructor with parameter type IResourceOperation). but i already configured all the details in structureMap . i am sure that my structuremap configuration is working 100% well expect the creation of this AclAuthorizationManager class.because i am able to to apply DI in other classes.
What is wrong part in my code?
in my experience when you specify the type constructor must say that inherits from the interface.
Therefore, you should replace this line:
ForConcreteType<AclAuthorizationManager>().Configure.Ctor<IResourceOperationAppService>()
By:
ForConcreteType<AclAuthorizationManager>().Configure.Ctor<IResourceOperationAppService>().Is<ResourceOperationAppService>()
Where is the implementation ResourceOperationAppService IResourceOperationAppService.

Unity Dependency Injection error - No parameterless constructor defined for this object

I have an application with a GenericHandler and would like to inject dependencies using Unity. No matter what I try I get the error:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean
I have tried to follow the example at http://geekswithblogs.net/Rhames/archive/2012/09/11/loosely-coupled-.net-cache-provider-using-dependency-injection.aspx.
My constructor for the handler is as follows:
public class GetPerson : IHttpHandler
{
private IPersonRepository repo;
public GetPerson(IPersonRepository repo)
{
this.repo = repo;
}
IPersonRepository is implemented by CachedPersonRepository. CachedPersonRepository wraps the PersonRepository (which is used for DataAccess if an item cannot be found in the cache). Both CachedPersonRepository and PersonRepository are IPersonRepository:
public class CachedPersonRepository : IPersonRepository
{
private ICacheProvider<Person> cacheProvider;
private IPersonRepository personRepository;
public CachedPersonRepository(IPersonRepository personRepository, ICacheProvider<Person> cacheProvider)
{
This IPersonRepository personRepository is parameterless.
ICacheProvider<Person> is implemented by MemcachedCacheProvider<T>:
public class MemcachedCacheProvider<T> : ICacheProvider<T>
{
public T Get(string key, Func<T> retrieveData, DateTime? absoluteExpiry, TimeSpan relativeExpiry)
{
I have tried unsuccessfully to initialise the Unity Container in my Global.asax file Application_Start. DI is new to me and I would very much appreciate any advice on where I'm going wrong.
There were actually two issues here.
Firstly, CachedPersonRepository uses the Decorator pattern which I didn't properly understand before. Once I understood this I was able to register and resolve the PersonRepository appropriately using this configuration:
public static void Configure(IUnityContainer container)
{
container.RegisterType<ICacheProvider<Person>, MemcachedCacheProvider<Person>>();
container.RegisterType<IPersonRepository, PersonRepository>("PersonRepository", new ContainerControlledLifetimeManager());
container.RegisterType<IPersonRepository, CachedPersonRepository>(
new InjectionConstructor(
new ResolvedParameter<IPersonRepository>("PersonRepository"),
new ResolvedParameter<ICacheProvider<Person>>()));
container.Resolve<IPersonRepository>();
}
Having fixed this I still saw the same "No parameterless constructor defined for this object" error.
The reason for this, is that I was working with an IHttpHandler and it is not possible to inject dependencies in the constructor.
I got around this by using Property injection:
A Repository property with the Dependency Attribute has been added to the GetPerson handler:
public class GetPerson : HandlerBase
{
[Dependency]
public IPersonRepository Repository { get; set; }
A new http module was needed to check for requests from handlers which implemented my HandlerBase:
public class UnityHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
}
public void Dispose() { }
private void OnPreRequestHandlerExecute(object sender, EventArgs e)
{
IHttpHandler currentHandler = HttpContext.Current.Handler as HandlerBase;
if (currentHandler != null)
{
HttpContext.Current.Application.GetContainer().BuildUp(
currentHandler.GetType(), currentHandler);
}
}
}
Resources:
http://download.microsoft.com/download/4/D/B/4DBC771D-9E24-4211-ADC5-65812115E52D/DependencyInjectionWithUnity.pdf (Chapter 4, pages 60-63)
http://msdn.microsoft.com/en-us/library/ff664534(v=pandp.50).aspx

WCF Runtime Error while using Constructor

I am new to WCF i am using constructor in my WCF service.svc.cs file....It throws this error when i use the constructor
The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor.
To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.
When i remove the constructor its working fine....But its compulsory that i have to use constructor...
This is my code
namespace UserAuthentication
{
[ServiceBehavior(InstanceContextMode=System.ServiceModel.InstanceContextMode.Single)]
public class UserAuthentication : UserRepository,IUserAuthentication
{
private ISqlMapper _mapper;
private IRoleRepository _roleRepository;
public UserAuthentication(ISqlMapper mapper): base(mapper)
{
_mapper = mapper;
_roleRepository = new RoleRepository(_mapper);
}
public string EduvisionLogin(EduvisionUser aUser, int SchoolID)
{
UserRepository sampleCode= new UserRepository(_mapper);
sampleCode.Login(aUser);
return "Login Success";
}
}
}
can anyone provide ideas or suggestions or sample code hw to resolve this issue...
You could add something like (if possible):
public UserAuth() : this(SqlMapperFactory.Create())
{
}

How can you inject an asp.net (mvc2) custom membership provider using Ninject?

OK, so I've been working on this for hours. I've found a couple of posts here, but nothing that actually resolves the problem. So, let me try it again...
I have an MVC2 app using Ninject and a custom membership provider.
If I try and inject the provider using the ctor, I get an error: 'No parameterless constructor defined for this object.'
public class MyMembershipProvider : MembershipProvider
{
IMyRepository _repository;
public MyMembershipProvider(IMyRepository repository)
{
_repository = repository;
}
I've also been playing around with factories and Initialize(), but everything is coming up blanks.
Any thoughts/examples?
The Membership provider model can only instantiate a configured provider when it has a default constructor. You might try this using the Service Locator pattern, instead of using Dependency Injection. Example:
public class MyMembershipProvider : MembershipProvider
{
IMyRepository _repository;
public MyMembershipProvider()
{
// This example uses the Common Service Locator as IoC facade, but
// you can change this to call NInject directly if you wish.
_repository = ServiceLocator.Current.GetInstance<IMyRepository>;
}
This is how I was able to do this:
1) I created a static helper class for Ninject
public static class NinjectHelper
{
public static readonly IKernel Kernel = new StandardKernel(new FooServices());
private class FooServices : NinjectModule
{
public override void Load()
{
Bind<IFooRepository>()
.To<EntityFooRepository>()
.WithConstructorArgument("connectionString",
ConfigurationManager.ConnectionStrings["FooDb"].ConnectionString);
}
}
}
2) Here is my Membership override:
public class FooMembershipProvider : MembershipProvider
{
private IFooRepository _FooRepository;
public FooMembershipProvider()
{
NinjectHelper.Kernel.Inject(this);
}
[Inject]
public IFooRepository Repository
{
set
{
_FooRepository = value;
}
}
...
With this approach it doesn't really matter when the Membership provider is instantiated.
I had the same problem at the exact same spot in the book. It wasn't until later on in the book that I noticed there were two separate web.config files. I initially placed my connectionString key in the wrong web.config file. It wasn't until I placed the connectionString in the correct web.config file that the 'no parameterless constructor' error went away.

Resources