I am using WCF web services and it was using OLD unity 2.0. So i updated Unity and other reference with latest version 5.0. I am getting exception:
Resolution failed with error: No public constructor is available for type xyz.Services.Contracts.Security.IAuthenticationService.
For more detailed information run Unity in debug mode: new UnityContainer().AddExtension(new Diagnostic())
Exception of type 'Unity.Exceptions.InvalidRegistrationException' was thrown.
Really i tried many things but not success. please any expert have a look.
asked Apr 26, 2020 at 19:04
3
I came across the same error upgrading from Unity version 3.5 to 5.11. In my case, during resolution the exception was the same ResolutionFailedException
with message «No public constructor is available for IMyInterface» and having the same inner exception InvalidRegistrationException
.
Well, the error messages and types of exceptions were misleading in my case; there was no registration problem nor did I ask for a public constructor for the interface. It seems that there has been a breaking change in the Resolve
method overload which takes an instance name. Null names are no longer equivalent to empty string names. Replace your empty string name to null or use the other overload which doesn’t specify an instance name:
var service = container.Resolve<xyz.Services.Contracts.Security.IAuthenticationService>();
OR
var service = container.Resolve<xyz.Services.Contracts.Security.IAuthenticationService>(null);
answered Jun 11, 2020 at 3:47
grammophonegrammophone
5715 silver badges8 bronze badges
I’m using Patterns and Practices’ Unity to inject dependencies into my objects and have hit a weird (to me, anyway) issue. Here’s my class definitions:
public class ImageManager : IImageManager
{
IImageFileManager fileManager;
public ImageManager(IImageFileManager fileMgr)
{
this.fileManager = fileMgr;
}
}
public class ImageFileManager : IImageFileManager
{
public ImageFileManager(string folder)
{
FileFolder = folder;
}
}
And here’s the code to register my classes
container.RegisterInstance<MainWindowViewModel>(new MainWindowViewModel())
.RegisterType<IPieceImageManager, PieceImageManager>(
new InjectionConstructor(typeof(string)))
.RegisterType<IImageFileManager, ImageFileManager>()
.RegisterType<IImageManager, ImageManager>(
new InjectionConstructor(typeof(IImageFileManager)));
I originally resolved this in the code behind (I know, it defeats the purpose. Bear with me.) of the XAML file like this
IImageManager imageManager = MvvmViewModelLocator.Container.Resolve<IImageManager>(
new ParameterOverride("folder", "/images"));
And it worked. But I created a view model for my main view and when I copied the same line into it, I get an exception. Here are the two most inner exceptions:
InnerException: Microsoft.Practices.Unity.ResolutionFailedException
HResult=-2146233088
Message=Resolution of the dependency failed, type = "SwapPuzzleApp.Model.IImageManager", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type IImageManager does not have an accessible constructor.
At the time of the exception, the container was:
Resolving SwapPuzzleApp.Model.IImageManager,(none)
Source=Microsoft.Practices.Unity
TypeRequested=IImageManager
StackTrace:
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container, ResolverOverride[] overrides)
at SwapPuzzleApp.ViewModel.MainWindowViewModel..ctor() in c:UsersCaroleDocumentsVisual Studio 2012ProjectsSwapPuzzleSwapPuzzleViewModelMainWindowViewModel.cs:line 17
at SwapPuzzleApp.ViewModel.MvvmViewModelLocator..cctor() in c:UsersCaroleDocumentsVisual Studio 2012ProjectsSwapPuzzleSwapPuzzleViewModelMvvmViewModelLocator.cs:line 51
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=The type IImageManager does not have an accessible constructor.
Source=Microsoft.Practices.Unity
StackTrace:
StackTrace:
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForNullExistingObject(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
InnerException:
I’m not sure what the problem is, as ImageManager clearly has a public constructor. I thought it might be due to an invalid path, but if I concretely instantiate the object, everything works.
// this line has no problems
IImageManager imageManager = new ImageManager(new ImageFileManager("/images"));
I also wondered if I needed to pass in new InjectionConstructor(typeof(string)) when I register IImageManager, but it doesn’t seem to help and why would it be needed now and not before? So I’m stumped. This is my first attempt at using Dependency Injection, so it’s probably something basic. I’m just not seeing what, though.
- Remove From My Forums
-
Question
-
User-1104215994 posted
Hello,
I have a web API and at first I had only one controller (api/v2/game) as follows;
[System.Web.Http.RoutePrefix("api/v2/game")] public class LoadTestController : ApiController { private readonly IGameServicesTest _gameServices; #region Public Constructor /// <summary> /// Public constructor to initialize game service instance /// </summary> public LoadTestController(IGameServicesTest gameServices) { _gameServices = gameServices; } #endregion // POST: api/Game //[RequireHttps] For Prod Only [ValidTimeFilter] [ValidProductCodeFilter] [ValidIntervalFilter] [ValidTotalDailySale] [ValidTerminalFilter] [HttpPost, Route("purchase")] public async Task<IHttpActionResult> PurchaseGame(RequestDto game){ ...
Now I added one more controller (api/v2/web/game) but requests couldn’t hit this new controller;
[System.Web.Http.RoutePrefix("api/v2/web/game")] public class PalasController : ApiController { private readonly IGameServicesWeb _gameServices; #region Public Constructor /// <summary> /// Public constructor to initialize game service instance /// </summary> public PalasController(IGameServicesWeb gameServices) { _gameServices = gameServices; } #endregion [ValidProductCodeFilter] [HttpPost, Route("purchase")] public async Task<IHttpActionResult> PurchaseGame(RequestDto game) { ...
Here is the webapiconfig;
public static void Register(HttpConfiguration config) { // Web API configuration and services config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local; // Web API routes config.MapHttpAttributeRoutes(); //Registering RequestResponseHandler config.MessageHandlers.Add(new RequestResponseHandler()); //Registering CustomExceptionFilter config.Filters.Add(new CustomExceptionFilter()); var resolver = config.DependencyResolver; var basicAuth = resolver.GetService(typeof(BasicAuthenticationAttribute)) as BasicAuthenticationAttribute; // Web API configuration and services config.Filters.Add(basicAuth); }
I am trying with postman but requests don’t reach the controller. What is missing?
Answers
-
User475983607 posted
There is not enough information to reproduce this issue.
I built a very basic RoutePrefix and Route test and the attributes work exactly as written in the reference documentation. Please take a few moments to debug your code.
URLs
https://localhost:44371/api/v2/game/purchase https://localhost:44371/api/v2/web/game/purchase
[System.Web.Http.RoutePrefix("api/v2/web/game")] public class PalasController : ApiController { // api/v2/web/game/purchase [HttpGet, Route("purchase")] public string PurchaseGame() { return "PalasController"; } }
// api/v2/game/ [RoutePrefix("api/v2/game")] public class LoadTestController : ApiController { // api/v2/game/purchase [HttpGet, Route("purchase")] public string PurchaseGame() { return "LoadTestController"; } }
API Route configuration
public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
-
Marked as answer by
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
-
User1686398519 posted
Hi cenk1536,
Has the problem you encountered at first been resolved?I have other solutions you can refer to it.
- Because you have defined the default routeTemplate, when you use
RoutePrefix, it will look for a matching routeTemplate. If you don’t define it, you won’t be able to find it.You need to
define routeTemplate in WebApiConfig.cs. - The order in which the routes are registered in the route table is important. Register more
specific routes first, and then register more general routes to avoid false matches.
WebApiConfig.cs
config.Routes.MapHttpRoute( name: "webgameApi", routeTemplate: "api/v2/web/game/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "gameApi", routeTemplate: "api/v2/game/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );
Best Regards,
YihuiSun
-
Marked as answer by
Anonymous
Thursday, October 7, 2021 12:00 AM
- Because you have defined the default routeTemplate, when you use
Unity Container ResolutionFailedException when the mapping is correct in the config file
I was using a ServiceLocator which i was DIing with Unity
This all worked fine, but I wanted lazy instantiation of the repositories as they have quite sparse use.
So my ServiceLocator now looks like
I’m now getting a really unhelpful ResolutionFailedException error
Resolution of the dependency failed, type = «DomainModel.DataServices.Interface.IUserStore», name = «». Exception message is: The current build operation (build key Build Key[DomainModel.DataServices.Interface.IUserStore, null]) failed: The current type, DomainModel.DataServices.Interface.IUserStore, is an interface and cannot be constructed. Are you missing a type mapping? (Strategy type BuildPlanStrategy, index 3)
Telling me my interface type cannot be instantiated because it is an interface is pretty pointless. I know it’s an interface, that’s why the container is supposed to be resolving it for me!
Anyway, the point to note here is that I know the type mapping in the config is fine, as when I was injecting the type interface directly instead of trying to lazy load, it resolved it with no problems.
What am I missing that means something somewhere has to change in order to lazy load this way?
Update: I am guessing what’s happening here, is that when I DI the container into the ServiceLocator, the «main» container is instantiating a new container each time which is then not configured properly. I think maybe I need some way to specify that I was to pass this in as the container, rather than resolve it with a new instantiation.
Источник
Resolution failed with error: No public constructor is available
I am using WCF web services and it was using OLD unity 2.0. So i updated Unity and other reference with latest version 5.0. I am getting exception:
Really i tried many things but not success. please any expert have a look.
1 Answer 1
I came across the same error upgrading from Unity version 3.5 to 5.11. In my case, during resolution the exception was the same ResolutionFailedException with message «No public constructor is available for IMyInterface» and having the same inner exception InvalidRegistrationException .
Well, the error messages and types of exceptions were misleading in my case; there was no registration problem nor did I ask for a public constructor for the interface. It seems that there has been a breaking change in the Resolve method overload which takes an instance name. Null names are no longer equivalent to empty string names. Replace your empty string name to null or use the other overload which doesn’t specify an instance name:
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.1.10.43142
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
Unity ResolutionFailedException for System.Web.Mvc Types
My WebApp is a combination of WebForms pages and MVC 4 pages.
Using Unity, I am getting the following exception.
Exception Type:
Message:
with an Inner Exception of:
Message:
Stack Trace:
I consistently get the same resolution exception for the following types:
In Application_Start, I am setting up the IoC with:
. where GetContainer returns all the registered types and UnityDependencyResolver is-a IDependencyResolver
Any ideas what is causing the issue?
1 Answer 1
I am not sure how the container instance returned by UnityConfigurator.GetContainer() behaves exactly, but I assume it tries to resolve by itself alone the ModelMetadataProvider when needed. This ModelMetadataProvider has some dependencies that your container does not know that only the initial MVC resolver can resolve. By ‘initial MVC resolver’ I mean the result of DependencyResolver.Current before you call DependencyResolver.SetResolver(. ) . So, you need to implement a proxy over your own container and use as fallback the initial MVC resolver.
A quick example of how the proxy’s implementation should look like:
And then, in Application_Start() you overwrite the MVC resolver with a instance of this proxy, like this:
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.1.10.43142
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
Unity’s ResolutionFailedException
I have an old Asp.Net web application using Unity for dependency injection. Today I updated the Unity using NuGet to the latest version. On trying to run the application, I am getting an exception:
Unity.Exceptions.ResolutionFailedException: ‘Resolution of the dependency failed, type = ‘SOME.Services.ISomeService’, name = ‘(none)’. Exception occurred while: while resolving. Exception is: InvalidOperationException — The property converter on type DAL.Repositories.SomeRepository is not settable.
The exception happened on line
I am very new to Unity. Could you please help?
1 Answer 1
The newer versions of Unity have breaking changes.
You may want to stick with the older versions of the DLL until you refactor the changes.
v4.0.1 Version 4.x is dead. Loss of original signing certificate made it impossible to release anything compatible with v4.0.1 release. To give original developers a credit only about 60 issues were found during two years in production. To move on and enable further development version v5 has been created.
v5.x Version 5.x is created as replacement for v4.0.1. Assemblies and namespaces are renamed and refactored but otherwise it is compatible with the original. v5.0.0 release fixes most of the issues found in v4.0.1 and implements several optimizations but the accent was on compatibility and if optimization would break API it was omitted. Once stabilized, this version will enter LTS status and will be patched and fixed for the next few years. There will be no significant development in this line.
Источник
Unity + C# — «Resolution of the dependency failed»
My application have a 10 WCFService ( WCFService Application on platform .NET Framework 3.5) with same software and hardware but only 1 takes this exception:
When user is logged in invoke this method:
with GetRegisteredService() implementation with ClientIdentifier = 0 for first execution
with IOC code implementation and Initilization:
i have this exception on execution method «Resolve»:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. —> Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = «ApCon.IService», name = «Anagxxx». Exception message is: The current build operation (build key Build Key[ApCon.StandardService, Anaxxxx]) failed: The current build operation (build key Build Key[ApCon.StandardService, Anaxxxx]) failed:Index was outside the bounds of the array. (Strategy type DynamicMethodConstructorStrategy, index 0) (Strategy type BuildPlanStrategy, index 3) —> Microsoft.Practices.ObjectBuilder2.BuildFailedException: The current build operation (build key Build Key[ApCon.StandardService, Anagrafe]) failed: The current build operation (build key Build Key[ApCon.StandardService, Anagrafe]) failed: Index was outside the bounds of the array. (Strategy type DynamicMethodConstructorStrategy, index 0) (Strategy type BuildPlanStrategy, index 3) —> Microsoft.Practices.ObjectBuilder2.BuildFailedException: The current build operation (build key Build Key[ApCon.StandardService, Anagxxx]) failed: Index was outside the bounds of the array. (Strategy type DynamicMethodConstructorStrategy, index 0) —> System.IndexOutOfRangeException: Index was outside the bounds of the array. at System.Collections.Generic.List1.Add(T item) at Microsoft.Practices.ObjectBuilder2.DependencyResolverTrackerPolicy.AddResolverKey(Object key) at Microsoft.Practices.ObjectBuilder2.ConstructorSelectorPolicyBase`1.CreateSelectedConstructor(IBuilderContext context, ConstructorInfo ctor) at Microsoft.Practices.ObjectBuilder2.ConstructorSelectorPolicyBase1.SelectConstructor(IBuilderContext context) at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.PreBuildUp(IBuilderContext context) at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) — End of inner exception stack trace — at
Could it be the lock instruction? It seems that types weren’t registered and isInitialized becomed true
Источник
I’m devolping a WPF application, using Prism 7.2. I have a module, which implements the IModule
interface, where I register the views and viewmodels in the RegisterTypes
method, e.g.:
containerRegistry.Register<IPanelOptimizationViewModel, PanelOptimizationViewModel>();
The problem arises when I try to resolve the implementation:
var vm = containerProvider.Resolve<IPanelOptimizationViewModel>();
whereupon I get the following Unity.ResolutionFailedException:
‘Resolution failed with error: No public constructor is available for type
XXX.Infrastructure.Interfaces.IView.’
The PanelOptimizationViewModel
class derives from a base class:
public class PanelOptimizationViewModel : ViewModelBase, IPanelOptimizationViewModel
{
public PanelOptimizationViewModel(IPanelOptimizationView view, IPanelOptimizationInputViewModel inpVM) : base(view)
}
and the ViewModelBase
looks like this:
public class ViewModelBase : BindableBase, IViewModel
{
public IView View { get; set; }
public ViewModelBase(IView view)
{
View = view;
View.ViewModel = this;
}
}
The interfaces IView
and IViewModel
are defined in a common Infrastructure project. They are not registered anywhere in the container, but if I remove the IPanelOptimizationInputViewModel
parameter, no runtime exception is thrown — leading me to think that I don’t need to do this, either.
As far as I have been able to understand, the Unity.Container
will use the «most parameterized» constructor (see Unity not using the default constructor of the class), but I cannot provide a parameter in the Register method to specify this, as one apparently could before (pre Prism 7’s container abstraction), with the RegisterType method.
How to solve this? Is there an overload of the Prism.Ioc.IContainerRegistry.Register method that allows me to set up the registration for constructor injection?
Should I work directly with the Unity container?
Basically, I am trying to inject a child view’s viewmodel into the constructor of my «main» viewmodel, but this does not go well as long as the wrong constructor is called on the base class, with the wrong set of parameters… (if that is what is happening).
Needless to say, all child views and viewmodels have been registered in the RegisterTypes method in the module.
Any help on this would be greatly appreciated
Web API Dependency Injection with Unity error — No public constructor is available for type System.Web.Http.Dispatcher.IHttpControllerActivator
I am trying to implement the dependency injection in ASP.Net web API with unity container and have implemented the exactly with below 2 articles:
- https://stackoverflow.com/a/38770689/3698716
- https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection
Both are related to each other with some minor change but implementation for both are the same.
After implementing I am getting an error in the method GetService in UnityResolver.cs class:
«Resolution failed with error: No public constructor is available for type System.Web.Http.Dispatcher.IHttpControllerActivator.»
Did you try the latest Unity?
Did you try the latest Unity?
I have used Unity 5.11.7 and Unity.WebAPI 5.4.0 versions, Those were the latest available version on the NuGet.
Unfortunately I know very little about Web API and cant’t really help. Try looking into history of this project for one of the examples.
If this doesn’t help perhaps this could give some clues.
Unfortunately I know very little about Web API and cant’t really help. Try looking into history of this project for one of the examples.
If this doesn’t help perhaps this could give some clues.
Unable to get any help with web API in the given examples.
If you want to integrate Unity with ASP.NET Web API, you have at least 3 choices:
-
Do it manually — this is what your links explain how to do by writing your own IDependencyResolver implementation.
-
Use my Unity.WebAPI library. It sounds as though you are already using this, in which case, you might want to look here. Judging by the error, it seems as though the dependency resolver has not been registered so I am wondering if you have missed out adding
UnityConfig.RegisterComponents();
to Application_Start()? -
Use Unity.AspNet.WebApi. I don’t know much about this but someone here may be able to help.
If you want to integrate Unity with ASP.NET Web API, you have at least 3 choices:
- Do it manually — this is what your links explain how to do by writing your own IDependencyResolver implementation.
- Use my Unity.WebAPI library. It sounds as though you are already using this, in which case, you might want to look here. Judging by the error, it seems as though the dependency resolver has not been registered so I am wondering if you have missed out adding
UnityConfig.RegisterComponents();
to Application_Start()?- Use Unity.AspNet.WebApi. I don’t know much about this but someone here may be able to help.
@devtrends I have done some minor changes in the code and I dont think those are making problem but now I am getting stackoverflow exception and my code is breaking, I have added my entire code base along with error here
@nadeem1990 is this an issue that is happening for every request or is it infrequent?