I am trying to create a concrete implementation of ILogger in python using the build in python logger.
However, when I try to implement the ILogger interface, I'm getting the exception
Method 'Log' in type 'Microsoft.Extensions.Logging.PyLogger' from assembly 'Python.Runtime.Dynamic, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
The code so far is simple and incomplete
class PyLogger(ILogger):
__namespace__ = "Microsoft.Extensions.Logging"
def Log(self, logLevel, eventId, state, exception, formatter):
print(logLevel, eventId, state, exception, formatter)
return
def IsEnabled(self):
return True
I don't understand why it doesn't like my Log definition.
When I inspect ILogger.Log it get the following, which looks complete.
>>> inspect.signature(ILogger.Log)
<Signature (logLevel, eventId, state, exception, formatter)>
Related
I need a way to send build events/progress during the build process.
All I have is roughly:
var proj = Microsoft.Build.Evaluation.Project(csprojDir);
var consoleLogger = new Microsoft.Build.Logging.ConsoleLogger();
proj.Build(consoleLogger);
But I can't find a way to handle events (e.g. some Action or delegate of any kind that receives events).
Any idea how catch those?
Write your own custom logger and pass an instance of your logger to the Build method. There are overloads of Build that accept an IEnumerable<ILogger> so you can pass both the consoleLogger and your custom logger.
ILogger defines an Initialize(IEventSource) method. IEventSource has the events you are probably looking for.
There is example code (the same example) in both the IEventSource Interface and ILogger Interface documentation.
I create a IWebHostBuilder like so:
public IWebHostBuilder GetWebHostBuilder()
{
return new WebHostBuilder().UseContentRoot(_contentRoot)
.ConfigureServices(InitializeServiceCollection)
.UseEnvironment(_environment)
.UseConfiguration(GetConfiguration())
.UseStartup(typeof(TStartup));
}
Here, the InitializeServiceCollection is implemented like so:
private void InitializeServiceCollection(IServiceCollection services)
{
var manager = new ApplicationPartManager();
manager.ApplicationParts.Add(new AssemblyPart(_assembly));
manager.FeatureProviders.Add(new ControllerFeatureProvider());
manager.FeatureProviders.Add(new ViewComponentFeatureProvider());
services.AddSingleton(manager);
}
Then I create the TestServer like so:
var myTestServer = new TestServer(GetWebHostBuilder());
Here I get the exception (full exception below). It gets thrown at services.AddAutoMapper(); method call in the system under test. However, when I run the system under test on it's own and test it manually with Postman, it's working fine and the object mapping with Automapper is working well too. It just raises the exception in the integration test.
Full exception:
System.AggregateException : One or more errors occurred. (Unable to load one or more of the requested types.
Could not load type 'Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalFullAnnotationNames' from assembly 'Microsoft.EntityFrameworkCore.Relational, Version=2.2.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.) (The following constructor parameters did not have matching fixture data: TestFixture fixture)
---- System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types.
Could not load type 'Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalFullAnnotationNames' from assembly 'Microsoft.EntityFrameworkCore.Relational, Version=2.2.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
---- The following constructor parameters did not have matching fixture data: TestFixture fixture
----- Inner Stack Trace #1 (System.Reflection.ReflectionTypeLoadException) -----
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeAssembly.get_DefinedTypes()
at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.ToArray()
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at AutoMapper.ServiceCollectionExtensions.AddAutoMapperClasses(IServiceCollection services, Action`2 configAction, IEnumerable`1 assembliesToScan) in xxx\automapper-extensions-microsoft-dependencyinjectio\src\AutoMapper.Extensions.Microsoft.DependencyInjection\ServiceCollectionExtensions.cs:line 72
at xxx.Startup.ConfigureServices(IServiceCollection services) in xxx\Startup.cs:line 35
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at Microsoft.AspNetCore.TestHost.TestServer..ctor(IWebHostBuilder builder, IFeatureCollection featureCollection)
at xxx.Tests.TestFixture.InitializeServer() in xxx.Tests\TestFixture.cs:line 67
at xxx.Tests.TestFixture..ctor() in xxx.Tests\TestFixture.cs:line 31
----- Inner Stack Trace #2 (Xunit.Sdk.TestClassException) -----
So, I managed to resolve the issue by replacing services.AddAutoMapper() with services.AddAutoMapper(Type[] types) overload. Not sure what is wrong with the original method, but in order to avoid that reflective call on the assemblies, I used this overload and it's working now.
I suddenly get errors while running the unit test for C# program in visual studio.
I guess the error appears after I added the System.Numerics.Vectors NuGet package, howewert the test I run does not use it yet.
Before adding it, the test run was fine.
I get following error:
for more details on managing these settings.
[1/13/2018 6:37:32 PM Informational] Test Adapter for Google Test: Test discovery starting...
[1/13/2018 6:37:32 PM Error] ERROR: Exception while discovering tests: System.AggregateException: One or more errors occurred. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at GoogleTestAdapter.DiaResolver.PeParser.<>c__DisplayClass4_0.<ProcessImports>b__0(LoadedImage image)
at GoogleTestAdapter.DiaResolver.PeParser.ParsePeFile(String executable, ILogger logger, Action`1 action)
at GoogleTestAdapter.DiaResolver.PeParser.ProcessImports(String executable, ILogger logger, Func`2 predicate)
at GoogleTestAdapter.DiaResolver.PeParser.FindImport(String executable, String import, StringComparison comparisonType, ILogger logger)
at GoogleTestAdapter.GoogleTestDiscoverer.IsGoogleTestExecutable(String executable, String customRegex, ILogger logger)
at GoogleTestAdapter.GoogleTestDiscoverer.<>c__DisplayClass6_0.<DiscoverTests>b__0()
at GoogleTestAdapter.Settings.SettingsWrapper.ExecuteWithSettingsForExecutable(String executable, Action action, ILogger logger)
at GoogleTestAdapter.GoogleTestDiscoverer.DiscoverTests(String executable, ITestFrameworkReporter reporter, SettingsWrapper settings, ILogger logger, IDiaResolverFactory diaResolverFactory)
at GoogleTestAdapter.GoogleTestDiscoverer.<>c__DisplayClass5_0.<DiscoverTests>b__1()
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.WaitAll(Task[] tasks, Int32 millisecondsTimeout, CancellationToken cancellationToken)
at GoogleTestAdapter.Helpers.Utils.SpawnAndWait(Action[] actions, Int32 timeoutInMs)
at GoogleTestAdapter.GoogleTestDiscoverer.DiscoverTests(IEnumerable`1 executables, ITestFrameworkReporter reporter)
at GoogleTestAdapter.TestAdapter.TestDiscoverer.DiscoverTests(IEnumerable`1 executables, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
---> (Inner Exception #0) System.NullReferenceException: Object reference not set to an instance of an object.
at GoogleTestAdapter.DiaResolver.PeParser.<>c__DisplayClass4_0.<ProcessImports>b__0(LoadedImage image)
at GoogleTestAdapter.DiaResolver.PeParser.ParsePeFile(String executable, ILogger logger, Action`1 action)
at GoogleTestAdapter.DiaResolver.PeParser.ProcessImports(String executable, ILogger logger, Func`2 predicate)
at GoogleTestAdapter.DiaResolver.PeParser.FindImport(String executable, String import, StringComparison comparisonType, ILogger logger)
at GoogleTestAdapter.GoogleTestDiscoverer.IsGoogleTestExecutable(String executable, String customRegex, ILogger logger)
at GoogleTestAdapter.GoogleTestDiscoverer.<>c__DisplayClass6_0.<DiscoverTests>b__0()
at GoogleTestAdapter.Settings.SettingsWrapper.ExecuteWithSettingsForExecutable(String executable, Action action, ILogger logger)
at GoogleTestAdapter.GoogleTestDiscoverer.DiscoverTests(String executable, ITestFrameworkReporter reporter, SettingsWrapper settings, ILogger logger, IDiaResolverFactory diaResolverFactory)
at GoogleTestAdapter.GoogleTestDiscoverer.<>c__DisplayClass5_0.<DiscoverTests>b__1()
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()<---
can someone give me advice pls?
To see it, it is enough to do :
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Console.WriteLine("hello");
}
}
Below code is to Initialize Dependency Injection Container in application global.asax
IUnityContainer container = new UnityContainerFactory().CreateConfiguredContainer();
var serviceLocator = new UnityServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => serviceLocator);
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
But application is always failing with parameter less constructor exception for
HomeController, below is the exception.
Resolution of the dependency failed, type = "MyApp.Web.Controllers.HomeController", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, Microsoft.Practices.ServiceLocation.IServiceLocator, is an interface and cannot be constructed. Are you missing a type mapping?
At the time of the exception, the container was:
Resolving MyApp.Web.Controllers.HomeController,(none)
Resolving parameter "serviceLocator" of constructor MyApp.Web.Controllers.HomeController(Microsoft.Practices.ServiceLocation.IServiceLocator serviceLocator)
Resolving Microsoft.Practices.ServiceLocation.IServiceLocator,(none)
Below is the inner exception of the exception.
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForAttemptingToConstructInterface(IBuilderContext context) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\Strategies\BuildPlan\DynamicMethod\Creation\DynamicMethodConstructorStrategy.cs:line 207
at BuildUp_Microsoft.Practices.ServiceLocation.IServiceLocator(IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\Strategies\BuildPlan\BuildPlanStrategy.cs:line 43
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\Strategies\StrategyChain.cs:line 112
at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\BuilderContext.cs:line 215
at BuildUp_MyApp.Web.Controllers.HomeController(IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\Strategies\BuildPlan\BuildPlanStrategy.cs:line 43
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\Strategies\StrategyChain.cs:line 112
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\UnityContainer.cs:line 511
Microsoft.Practices.Unity 2.0.414.0 has been used. What is the issue with implementation, am I missing something?
You need to register all interfaces your controller relies on. In this case
HomeController(Microsoft.Practices.ServiceLocation.IServiceLocator serviceLocator) {...}
Means you need to have line like
container.RegisterType<IServiceLocator, SomeServiceLocatorImpl>();
Note that it is generally better practice to depend on required interfaces instead on IServiceLocator - How to avoid Service Locator Anti-Pattern?
Your constructor presumably has the following signature
public class HomeController : Controller
{
public HomeController( IServiceLocator locator )
{
...
Unity follows the signature and tries to find a concrete type mapped to the interface, registered in your container. But there is none.
What you do however, is a mistake. You should be injecting actual dependencies to services / business objects, not to the infrastructure class a service locator is.
public HomeController( ISomeService service, IAnotherService another )
Unity would resolve these, assuming you first map abstractions to concrete types.
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:\Users\Carole\Documents\Visual Studio 2012\Projects\SwapPuzzle\SwapPuzzle\ViewModel\MainWindowViewModel.cs:line 17
at SwapPuzzleApp.ViewModel.MvvmViewModelLocator..cctor() in c:\Users\Carole\Documents\Visual Studio 2012\Projects\SwapPuzzle\SwapPuzzle\ViewModel\MvvmViewModelLocator.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.
Look very closely at the error message. Notice this part:
Message=The type IImageManager does not have an accessible constructor.
Notice the type name is IImageManager, not ImageManager. Somewhere along the line you lost your type mapping.
Your registration of FileImageManager has a problem as well, since you don't specify the folder parameter in the registration, so Unity has no idea what string to pass.
I was using the examples in this article as my guide. Either the examples in there are way too advanced for an introduction, or there's misinformation in that topic.
After consulting other sources (mainly PluarlSight), I came up with a much simpler and more logical solution.
container.RegisterInstance<TimerViewModel>(new TimerViewModel());
container.RegisterType<IPieceImageManager, PieceImageManager>();
container.RegisterType<IImageFileManager, ImageFileManager>
(new InjectionConstructor("/images"));
container.RegisterType<IImageManager, ImageManager>();
I ran into a similar issue with this error tied directly to a Mock (using automoq) that I was doing for an operation. In this case it turned out that because there were a number of member methods that get called with the object being mocked, that I had to define all of those in the automoq chain to get it to resolve properly
I realize this is an example in instance code, but it could occur in Moqs also. So if you read this and are wondering about an example related to Moqs, look into that first.