Pradees
Pradees

Reputation: 201

Unity Dependency injection automatically expires after a particular time.. Why?

I am using Microsoft Unity for dependency injection in my Web api 2.0. It works properly; but some times it throws dependancy fails error. Same issue in published port as well as in local project. I am using Repository pattern in DDD concept... my dependency code in unit.config is given below.

var container = new UnityContainer();

container.RegisterType<ILogger, Log4NetLogger>();
container.RegisterType<NHibernateFactory, NHibernateFactory>();
container.RegisterType<INhibernateUnitOfWork, NHUnitOfWork>();
container.RegisterType(typeof(IRepository<,>), typeof(NHRepository<,>));

container.RegisterTypes(AllClasses.FromLoadedAssemblies(), 
    WithMappings.FromMatchingInterface, 
    WithName.Default, 
    WithLifetime.Hierarchical);

GlobalConfiguration.Configuration.DependencyResolver = 
    new UnityDependencyResolver(container);

I am getting the following error

2017-03-24 09:47:12,426 [12] ERROR Main - System.InvalidOperationException: An error occurred when trying to create a controller of type 'ProductController'. Make sure that the controller has a parameterless public constructor. ---> Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = "Solver.ERP.WebAPI.HMS.Controllers.V1.Masters.ProductController", name = "(none)". Exception occurred while: while resolving.

Exception is: InvalidOperationException - The current type, Solver.ERP.Application.Services.IProductService, is an interface and cannot be constructed. Are you missing a type mapping?

At the time of the exception, the container was:

Resolving Solver.ERP.WebAPI.HMS.Controllers.V1.Masters.ProductController,(none) Resolving parameter "PService" of constructor Solver.ERP.WebAPI.HMS.Controllers.V1.Masters.ProductController(Solver.ERP.Application.Services.IProductService PService, Solver.ERP.Infrastructure.Utility.Logging.ILogger Nlogger) Resolving Solver.ERP.Application.Services.IProductService,(none) ---> System.InvalidOperationException: The current type, Solver.ERP.Application.Services.IProductService, is an interface and cannot be constructed. Are you missing a type mapping? at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForAttemptingToConstructInterface(IBuilderContext context) at lambda_method(Closure , IBuilderContext ) at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.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.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) at lambda_method(Closure , IBuilderContext ) at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.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, IEnumerable1 resolverOverrides) --- End of inner exception stack trace --- at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable1 resolverOverrides) at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides) at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve(IUnityContainer container, Type t, ResolverOverride[] overrides) at Unity.WebApi.UnityDependencyScope.GetService(Type serviceType) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) --- End of inner exception stack trace --- at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request) at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()

Below code is using for mapping classes to interface

container.RegisterTypes(AllClasses.FromLoadedAssemblies(), WithMappings.FromMatchingInterface, WithName.Default, WithLifetime.Hierarchical);

Upvotes: 0

Views: 874

Answers (1)

Kgn-web
Kgn-web

Reputation: 7555

Looking at the Error message you provided.

ERROR Main - System.InvalidOperationException: An error occurred when trying to create a controller of type 'ProductController'. Make sure that the controller has a parameterless public constructor. --->

The error is quite common.You missed to instantiate your controller.

I am not sure about the syntax using Unityblock. But I know CastleWindsor DI container.

Please add the respective Unity configuration in your class.

container.Register(Classes.FromThisAssembly()
            .BasedOn(typeof(Controller))
            .If(t => t.Name.EndsWith("Controller"))
            .LifestyleTransient());
             //LifestylePerWebRequest or per thread decide as per your need.

Hope it helps :)

Upvotes: 1

Related Questions