For some reason, I get exception during instantiation of the home controller. I am very puzzled by it. I am thinking that may be it is caused by the different life time scope of the different dependencies - InstancePerDependency and SingleInstance.
using: Autofac.4.0.0
In my Register(). I have:
builder.Register(x => new DepositEligibilityService()).As<IDepositEligibilityService>().InstancePerDependency();
builder.Register(x => new SemanticExceptionManager()).As<IExceptionManager>().SingleInstance();
builder.Register(x => new SemanticLoggingManager()).As<ILoggingManager>().SingleInstance();
and
public class HomeController : BaseController
{
private readonly IAuthenticationManager _authenticationManager;
LoginInfo _loginInfo;
public HomeController(IDepositEligibilityService depositEligibilityService, IExceptionManager exceptionManager, ILoggingManager loggingManager):base(depositEligibilityService, exceptionManager, loggingManager)
{
// ...
}
}
I sometimes get an exception like the following:
Exception information:
Exception type: DependencyResolutionException
Exception message: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = HomeController (ReflectionActivator), Services = [DepositEligibility.Web.Controllers.HomeController], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An exception was thrown while invoking the constructor 'Void .ctor(DepositEligibility.Web.Services.IDepositEligibilityService, Gdot.Services.SemanticLogging.Interfaces.IExceptionManager, Gdot.Services.SemanticLogging.Interfaces.ILoggingManager)' on type 'HomeController'. ---> Object reference not set to an instance of an object. (See inner exception for details.) (See inner exception for details.)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Execute()
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance)
at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters)
at System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType)
An exception was thrown while invoking the constructor 'Void .ctor(DepositEligibility.Web.Services.IDepositEligibilityService, Gdot.Services.SemanticLogging.Interfaces.IExceptionManager, Gdot.Services.SemanticLogging.Interfaces.ILoggingManager)' on type 'HomeController'. ---> Object reference not set to an instance of an object. (See inner exception for details.)
at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate()
at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
Object reference not set to an instance of an object.
at DepositEligibility.Web.Controllers.BaseController..ctor(IDepositEligibilityService depositEligibilityService, IExceptionManager exceptionManager, ILoggingManager loggingManage)
at DepositEligibility.Web.Controllers.HomeController..ctor(IDepositEligibilityService depositEligibilityService, IExceptionManager exceptionManager, ILoggingManager loggingManager)
at lambda_method(Closure , Object[] )
at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate()
Related
In the following test code, I make a declaration: when the get() method is called with argument 0, then an exception should be thrown out. In my opinion, if the argument is not 0, the exception should not be thrown out. But, the test was passed. That means get(1) has caused an exception was thrown. Is this a bug of Mockito?
#RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
#Mock
private List<Integer> mockedList;
#Test(expected = Exception.class)
public void test() throws Exception {
when(mockedList.get(0)).thenThrow(new Exception());
mockedList.get(1);
}
}
You set up your test incorrectly and misinterpreted the outcome of your test.
The problem lies in the line:
when(mockedList.get(0)).thenThrow(new Exception());
The signature of "get" method does not allow checked excetions.
Thus, when you pass a checked exception to thenThrow, Mockito rightfully reports it with:
org.mockito.exceptions.base.MockitoException:
Checked exception is invalid for this method!
Invalid: java.lang.Exception
Thus the exception reported is MockitoException, not the Exception you passed to thenThrow. It is thrown even if you omit a call to mockedList.get(1);
To fix, use a RuntimeException, preferrably one that can be reported by get.
when(mockedList.get(0)).thenThrow(new IndexOutOfBoundsException());
Note that you stub a call that is not made afterwards, you need to use a lenient mock with #Mock(lenient = true), otherwise Mockito will report a org.mockito.exceptions.misusing.UnnecessaryStubbingException
I can't resolve ILogger instance in my console application...
I'm using Unity IoC and Serilog.
The registration is done like this:
container = new UnityContainer();
container.RegisterFactory<ILogger>(factory =>
{
ILogger log = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
return log;
}, new ContainerControlledLifetimeManager());
And then when I try this:
var logger = container.Resolve<ILogger>();
I get an exception:
Unity.ResolutionFailedException HResult=0x80131500 Message=Failed
to select a constructor for Serilog.Core.Logger
_____________________________________________________ Exception occurred while:
•resolving type: 'ILogger' mapped to 'Logger'
Source=Unity.Container StackTrace: at
Unity.UnityContainer.ExecuteValidatingPlan(BuilderContext& context)
at Unity.UnityContainer.Unity.IUnityContainer.Resolve(Type type,
String name, ResolverOverride[] overrides) at
Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container,
ResolverOverride[] overrides)
Inner Exception 1: InvalidOperationException: Failed to select a
constructor for Serilog.Core.Logger
Inner Exception 2: InvalidRegistrationException: Exception of type
'Unity.Exceptions.InvalidRegistrationException' was thrown.
I even tried registering it like this:
container = new UnityContainer();
ILogger log = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
container.RegisterInstance<ILogger>(log);
but with the same resulting exception thrown.
Please help
Found the problem...
The problem was this line of code down the road, overriding my configuration:
container.RegisterTypes(AllClasses.FromAssembliesInBasePath(), WithMappings.FromMatchingInterface, WithName.Default);
I have a Spring controller annotated class which implements this method:
#RequestMapping(value = "/event/eventList", method = RequestMethod.GET)
public #ResponseBody List<Event> listEvents() {
System.out.println("############ LIST EVENTS ############");
List<Event> events = eventService.listAllEvents();
for(Event event : events) {
Hibernate.getClass(event);
System.out.println(event);
}
return events;
}
when I call the page (localhost:8080/myapp/event/eventList) from browser, the method will be called correctly i see all the logs and the events are printed correctly meaning the event list is not empty and valid, but I get the error:
GRAVE: Servlet.service() for servlet [dispatcher] in context with path [/myapp] threw exception [Request processing failed; nested exception is java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?] with root cause
java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?
It does not return any Json representation.
I changed the method to return a string like:
#RequestMapping(value = "/event/eventList", method = RequestMethod.GET)
public #ResponseBody String listEvents() {
return "{'pippo':1}";
}
In this case the browser show the string correctly.
did I miss something?
The exception is thrown by com.google.gson.internal.bind.TypeAdapters when GSON is trying to serialize variable 'events' to Json.
This happens, cause
eventService.listAllEvents()
returns not a list already containing all events, but hibernate proxy that will do that lazy, when the list is actually used.
GSON does not know how to serialize that proxy.
Hibernate.getClass should initialize the underlying object as a side effect.
You need to call it also for the List 'events' itself, not only for every single event. The List can be a hibernate proxy also.
You may find more info on that topic at
Could not serialize object cause of HibernateProxy
I have a few actions in my .NET MVC application that go through a decent amount of data and return a JSON object to my views. In order to speed things up a little bit, I've started caching the JSON objects and returning those instead of going through all of the data if only a short time has passed:
System.Web.HttpContext.Current.Cache.Insert(System.Web.HttpContext.Current.User.Identity.Name + "WB", result, null, DateTime.UtcNow.AddMinutes(1), TimeSpan.Zero);
// result is the object that gets converted to JSON
result = new
{
TopDepartures = TopDepartures.ToArray(),
YesterdayFlights = YesterdayFlights.Count(),
TodayFlights = TodayFlights.Count(),
TomorrowFlights = TomorrowFlights.Count(),
LastMonthPax = LastMonthPax.ToString("#,##0"),
YesterdayPax = YesterdayPax.ToString("#,##0"),
PaxMonthToDate = PaxMonthToDate.ToString("#,##0"),
FirstCheckInLocalTime = FirstCheckIn.EstimatedCheckIn.ToString("HH:mm"),
FirstCheckInOrigin = FirstCheckIn.OriginIATA,
FirstCheckInDestination = FirstCheckIn.DestinationIATA,
FirstCheckInSDT = FirstCheckIn.ScheduledDepartureTime.ToString("HH:mm"),
FirstCheckInSAT = FirstCheckIn.ScheduledArrivalTime.ToString("HH:mm"),
FirstCheckInFlightNo = FirstCheckIn.CarrierCode + " " + FirstCheckIn.FlightNo,
LastCheckInLocalTime = LastCheckIn.EstimatedCheckIn.ToString("HH:mm"),
LastCheckInOrigin = LastCheckIn.OriginIATA,
LastCheckInDestination = LastCheckIn.DestinationIATA,
LastCheckInSDT = LastCheckIn.ScheduledDepartureTime.ToString("HH:mm"),
LastCheckInSAT = LastCheckIn.ScheduledArrivalTime.ToString("HH:mm"),
LastCheckInFlightNo = LastCheckIn.CarrierCode + " " + LastCheckIn.FlightNo,
TomorrowFirstCheckInLocalTime = TomorrowFirstCheckIn.EstimatedCheckIn.ToString("HH:mm"),
TomorrowFirstCheckInOrigin = TomorrowFirstCheckIn.OriginIATA,
TomorrowFirstCheckInDestination = TomorrowFirstCheckIn.DestinationIATA,
TomorrowFirstCheckInSDT = TomorrowFirstCheckIn.ScheduledDepartureTime.ToString("HH:mm"),
TomorrowFirstCheckInSAT = TomorrowFirstCheckIn.ScheduledArrivalTime.ToString("HH:mm"),
TomorrowFirstCheckInFlightNo = TomorrowFirstCheckIn.CarrierCode + " " + TomorrowFirstCheckIn.FlightNo,
};
I do a check at the beginning of the Action:
var cachedResult = System.Web.HttpContext.Current.Cache.Get(System.Web.HttpContext.Current.User.Identity.Name + "WB");
if (cachedResult != null)
{
return Json(cachedResult, JsonRequestBehavior.AllowGet);
}
The problem is, ever since I implemented this, Ninject has been periodically firing OutOfMemory exceptions. I've been researching this but I haven't been able to find anything explicitly referencing a link between caching and Ninject OutOfMemory exceptions. There also doesn't appear to be a specific pattern that causes the exception to be fired. It will run fine for hours of changes and testing and then suddenly the site will stop working and I'll see the OutOfMemory exception in the logs. Then other times it'll happen immediately.
This Action is called and the object retrieved by an AJAX call on my view, if that information is relevant.
Here is the stack trace:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.Collections.Generic.HashSet`1.SetCapacity(Int32 newSize, Boolean forceNewHashCodes)
at System.Collections.Generic.HashSet`1.IncreaseCapacity()
at System.Collections.Generic.HashSet`1.AddIfNotPresent(T value)
at System.Collections.Generic.HashSet`1.Add(T item)
at Ninject.Activation.Caching.ActivationCache.AddActivatedInstance(Object instance)
at Ninject.Activation.Strategies.ActivationCacheStrategy.Activate(IContext context, InstanceReference reference)
at Ninject.Activation.Pipeline.<>c__DisplayClass2.<Activate>b__0(IActivationStrategy s)
at Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map[T](IEnumerable`1 series, Action`1 action)
at Ninject.Activation.Pipeline.Activate(IContext context, InstanceReference reference)
at Ninject.Activation.Context.ResolveInternal(Object scope)
at Ninject.Activation.Context.Resolve()
at Ninject.KernelBase.<>c__DisplayClass15.<Resolve>b__f(IBinding binding)
at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
at System.Linq.Enumerable.<CastIterator>d__94`1.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at Ninject.Infrastructure.Language.ExtensionsForIEnumerable.ToArraySlow(IEnumerable series, Type elementType)
at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent)
at Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target)
at Ninject.Activation.Providers.StandardProvider.<>c__DisplayClass4.<Create>b__2(ITarget target)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Ninject.Activation.Providers.StandardProvider.Create(IContext context)
at Ninject.Activation.Context.ResolveInternal(Object scope)
at Ninject.Activation.Context.Resolve()
at Ninject.KernelBase.<>c__DisplayClass15.<Resolve>b__f(IBinding binding)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at Ninject.Planning.Targets.Target`1.GetValue(Type service, IContext parent)
at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent)
at Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target)
at Ninject.Activation.Providers.StandardProvider.<>c__DisplayClass4.<Create>b__2(ITarget target)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Ninject.Activation.Providers.StandardProvider.Create(IContext context)
at Ninject.Activation.Context.ResolveInternal(Object scope)
at Ninject.Activation.Context.Resolve()
at Ninject.KernelBase.<>c__DisplayClass15.<Resolve>b__f(IBinding binding)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at Ninject.ResolutionExtensions.Get(IResolutionRoot root, Type service, IParameter[] parameters)
at AirlineChoiceDashboard.WebUI.Infrastructure.NinjectControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) in D:\Development\Airline Choice Dashboard\Source Code\Development\WebUI\Infrastructure\NinjectControllerFactory.cs:line 38
I am trying to run IronPython code with c#.
I created a simple console application (.net 4) and added IronPython.dll , IronPython.Modules.dll and Microsoft.Scripting and wrote the next code -
using Microsoft.Scripting.Hosting;
namespace app
{
class Program
{
static void Main(string[] args)
{
ScriptRuntime runtime = IronPython.Hosting.Python.CreateRuntime();
ScriptEngine engine = runtime.GetEngine("py");
engine.Execute("print 'hello!'");
}
}
}
While trying to run this , I get an exception -
Unhandled Exception:
System.Reflection.TargetInvocationException:
Exception has been thrown by the
target of an invocation. --->
System.IO.FileNotFoundException :
Could not load file or assembly
'Microsoft.Scripting, Version=1.0.0.0,
Culture
=neutral, PublicKeyToken=31bf3856ad364e35' or
one of its dependencies. The syste m
cannot find the file specified. at
Core.LanguageProvider.Python..ctor(Stream
stream) --- End of inner exception
stack trace --- at
System.RuntimeMethodHandle._InvokeConstructor(IRuntimeMethodInfo
method, O bject[] args,
SignatureStruct& signature,
RuntimeType declaringType) at
System.RuntimeMethodHandle.InvokeConstructor(IRuntimeMethodInfo
method, Ob ject[] args,
SignatureStruct signature, RuntimeType
declaringType) at
System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags
invokeAttr, B inder binder, Object[]
parameters, CultureInfo culture) at
System.RuntimeType.CreateInstanceImpl(BindingFlags
bindingAttr, Binder bin der, Object[]
args, CultureInfo culture, Object[]
activationAttributes) at
System.Activator.CreateInstance(Type
type, BindingFlags bindingAttr, Binde
r binder, Object[] args, CultureInfo
culture, Object[]
activationAttributes) at
System.Activator.CreateInstance(Type
type, Object[] args) at
Core.LanguageRuntime.RegisterLanguageProvider(Type
providerType) in D:\cod
e\CodeRunner\Core\LanguageRuntime.cs:line
30 at Test.Program.Main(String[]
args) in
D:\code\CodeRunner\Test\Program.cs:lin
e 19 Press any key to continue . . .
I really , dont know what to do , searched at google and dont find a solution.
I will be glad to get help.
Whic version of iron python are you using ? The syntax you show seems belong to an older version, now you should have something like:
var ipy = Python.CreateRuntime();
anyway this blog post seems to be really accurate on pointing the correct reference to use. Anyway, ensure you have the latest IronPython version.