GithubHelp home page GithubHelp logo

jasperfx / lamar Goto Github PK

View Code? Open in Web Editor NEW
563.0 23.0 118.0 8.8 MB

Fast Inversion of Control Tool and Successor to StructureMap

Home Page: https://jasperfx.github.io/lamar

License: MIT License

C# 98.90% HTML 0.94% CSS 0.12% JavaScript 0.03% Batchfile 0.01% PowerShell 0.01% Shell 0.01%

lamar's Introduction

Lamar is going to be discontinued in the near future. It's Microsoft's world, and we're all just living in it

It's time to start a discussion about what if anything we could do on the way out the door to help folks eventually move off of Lamar and onto probably just the built in DI container

Lamar (née BlueMilk)

Discord

Fast Inversion of Control Tool

See the documentation website for more information.

Support Plans

JasperFx logo

While Lamar is open source, JasperFx Software offers paid support and consulting contracts for Lamar.

Working with the Code

There's really not much to it. Just open the Lamar.sln file in the IDE of your choice and go to town.

lamar's People

Contributors

aaronallbright avatar anaximander23 avatar aomader avatar cheng93 avatar chunty avatar danspam avatar dependabot[bot] avatar diegostamigni avatar gitter-badger avatar hammdo avatar hawxy avatar jeremydmiller avatar jokokko avatar jordy-bencom avatar kmbell avatar kutensky avatar mjohnsonkansys avatar mysticmind avatar nimafx avatar oskardudycz avatar pondidum avatar psampaio avatar pwhe23 avatar rizi avatar robi26 avatar seanterry avatar thomasskyldahl avatar tomstylesncc avatar vlatkozmejkoski avatar yassinebennani avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lamar's Issues

Resolving (seemingly) bi-directional dependency blows up on SOE

To repro:

public interface If { }

public class N : If
{
	public N(IEnumerable<If> n)
	{
	}
}

var container = new Container(x =>
{
	x.For<N>().Use(ctx => new N(Enumerable.Empty<If>()));

	x.For<If>().Use<N>();
});

var instance = container.GetInstance<If>();

blows up on SOE. On fixing this, is warning about bi-directional dependency desired or should N be constructed as defined in the expression? How about default policy on constructing such IEnumerable ctor args by omitting types that are of the same as the type being constructed?

Obviously SOE should not happen... Can be worked around by configuring explicit LambdaInstance for constructing If or IEnumerable<If>. I believe StructureMap's Forward was also a way to work around this problem.

Scope.QuickBuild an instance with inline values fails

Found this one in Jasper usage. Little hard to reproduce, but...

  1. Create a registration of ILogger where the concrete type has an inline dependency (found this through decorators)
  2. QuickResolve a concrete type that depends on ILogger

Compilation failure when using IdentityServer4.AccessTokenValidation (optional parameters)

Any input or direction in solving would be appreciated. This is currently a blocker for a rather large migration from structuremap to lamar.

some references since the Microsoft namespace is used in the projects directly:
https://github.com/IdentityServer/IdentityServer4.AccessTokenValidation/blob/29ed50c5b5950e7dde5efdce81dea4c774d20db0/src/IdentityServer4.AccessTokenValidation/IdentityServerAuthenticationExtensions.cs

https://github.com/IdentityModel/IdentityModel.AspNetCore.OAuth2Introspection/blob/94b0ccb4d5723b3992c05bf229cb1c476f280c3a/src/IdentityModel.AspNetCore.OAuth2Introspection/OAuth2IntrospectionOptions.cs

Message: System.InvalidOperationException : Compilation failures!

CS1746: The delegate 'Func<IDistributedCache, IPostConfigureOptions>' does not have a parameter named 'cache'

 // START: Microsoft_Extensions_Options_IPostConfigureOptions_Microsoft_AspNetCore_Builder_OAuth2IntrospectionOptions__postConfigureOAuth2IntrospectionOptions
    public class Microsoft_Extensions_Options_IPostConfigureOptions_Microsoft_AspNetCore_Builder_OAuth2IntrospectionOptions__postConfigureOAuth2IntrospectionOptions : Lamar.IoC.Resolvers.SingletonResolver<object>
    {
        private readonly IDistributedCache _distributedCache;
        private readonly Func<Microsoft.Extensions.Caching.Distributed.IDistributedCache, Microsoft.Extensions.Options.IPostConfigureOptions<Microsoft.AspNetCore.Builder.OAuth2IntrospectionOptions>> _func_of_IDistributedCache_IPostConfigureOptions_Microsoft_AspNetCore_Builder_OAuth2IntrospectionOptions_;
        private readonly Scope _topLevelScope;

        public Microsoft_Extensions_Options_IPostConfigureOptions_Microsoft_AspNetCore_Builder_OAuth2IntrospectionOptions__postConfigureOAuth2IntrospectionOptions(IDistributedCache distributedCache, Func<Microsoft.Extensions.Caching.Distributed.IDistributedCache, Microsoft.Extensions.Options.IPostConfigureOptions<Microsoft.AspNetCore.Builder.OAuth2IntrospectionOptions>> func_of_IDistributedCache_IPostConfigureOptions_Microsoft_AspNetCore_Builder_OAuth2IntrospectionOptions_, Scope topLevelScope) : base(topLevelScope)
        {
            _distributedCache = distributedCache;
            _func_of_IDistributedCache_IPostConfigureOptions_Microsoft_AspNetCore_Builder_OAuth2IntrospectionOptions_ = func_of_IDistributedCache_IPostConfigureOptions_Microsoft_AspNetCore_Builder_OAuth2IntrospectionOptions_;
            _topLevelScope = topLevelScope;
        }



        public override object Build(Lamar.IoC.Scope scope)
        {
            return _func_of_IDistributedCache_IPostConfigureOptions_Microsoft_AspNetCore_Builder_OAuth2IntrospectionOptions_(cache: _distributedCache);
        }

    }

    // END: Microsoft_Extensions_Options_IPostConfigureOptions_Microsoft_AspNetCore_Builder_OAuth2IntrospectionOptions__postConfigureOAuth2IntrospectionOptions

How to replicate:

In Lamar.AspNetCoreTests

  1. Install IdentityServer4.AccessTokenValidation 2.6.0
  2. In integration_with_aspnetcore.cs-ConfigureContainer line 174 Change to
services.AddAuthentication()
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "auth";
                options.RequireHttpsMetadata = true;
            });

Run Test: use_in_app

How to eliminate error message (temporary workaround):

Able to get things to compile by editing OptionalArgumentVariable.Usage to remove the parameter name. I went as far as to remove the parameter name when there was only one matching constructor in ContructorInstance.DetermineConstructor.

Changed return $"{_parameter.Name}: {_inner.Usage}"; to return _inner.Usage;

Lifecycle management

Do you have any plans for the types of lifecycle that Lamar would be supporting? Are you planning to bring all of the SM ones to Lamar or will there be a subset?

Compilation error when using the RazorEngine package

I am using RazorEngine https://github.com/Antaris/RazorEngine and if I try to use lamar with this then you get a compilation error when the asp.net site starts (CS0118: 'RazorEngine' is a namespace but is used like a type).

I guess the issue is related to #51 in the fact that the lack of explicit namespaces in the generated code is causing conflicts.

A failing unit test is here: https://github.com/danspam/lamar/tree/razorengine-issue

I will try to see if I can figure out a fix for this and add a PR, although if this is the same type of issue as #51 then perhaps a more extensive fix in the code generation is needed that will cover other similar cases?

Issue with generated variable name when using generics with multiple args

I am trying to use the latest SignalR with Asp.net Core 2.1 RC.
and Lamar, v0.9.7
Lamar.Microsoft.Dep[endencyInjection 0.9.6.

I have attached a simple Asp.Core test app I used to reproduce the problem.

When I try to run the app Lamar is throwing an exception with the following information.
Compilation failures!

CS1001: Identifier expected
CS1002: ; expected
CS1513: } expected
CS1002: ; expected
CS1513: } expected
CS1002: ; expected
CS1513: } expected
CS0246: The type or namespace name 'TestApp_INotifyHubClient_' could not be found (are you missing a using directive or an assembly reference?)
CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement

The generated code causing the error is:

// START: Microsoft_AspNetCore_SignalR_IHubContext_TestApp_TestHub_TestApp_INotifyHubClient__hubContext
     public class Microsoft_AspNetCore_SignalR_IHubContext_TestApp_TestHub_TestApp_INotifyHubClient__hubContext : Lamar.IoC.Resolvers.SingletonResolver<object>
     {
         private readonly HubLifetimeManager<TestApp.TestHub> _hubLifetimeManager_of_TestHub;
         private readonly Func<Microsoft.AspNetCore.SignalR.HubLifetimeManager<TestApp.TestHub>, Microsoft.AspNetCore.SignalR.IHubContext<TestApp.TestHub, TestApp.INotifyHubClient>> _func_of_HubLifetimeManager_TestApp_TestHub__IHubContext_TestApp_TestHub, TestApp_INotifyHubClient_;
         private readonly Scope _topLevelScope;
 
         public Microsoft_AspNetCore_SignalR_IHubContext_TestApp_TestHub_TestApp_INotifyHubClient__hubContext(HubLifetimeManager<TestApp.TestHub> hubLifetimeManager_of_TestHub, Func<Microsoft.AspNetCore.SignalR.HubLifetimeManager<TestApp.TestHub>, Microsoft.AspNetCore.SignalR.IHubContext<TestApp.TestHub, TestApp.INotifyHubClient>> func_of_HubLifetimeManager_TestApp_TestHub__IHubContext_TestApp_TestHub, TestApp_INotifyHubClient_, Scope topLevelScope) : base(topLevelScope)
         {
             _hubLifetimeManager_of_TestHub = hubLifetimeManager_of_TestHub;
             _func_of_HubLifetimeManager_TestApp_TestHub__IHubContext_TestApp_TestHub, TestApp_INotifyHubClient_ = func_of_HubLifetimeManager_TestApp_TestHub__IHubContext_TestApp_TestHub, TestApp_INotifyHubClient_;
             _topLevelScope = topLevelScope;
         }
 
         public override object Build(Lamar.IoC.Scope scope)
         {
             return _func_of_HubLifetimeManager_TestApp_TestHub__IHubContext_TestApp_TestHub, TestApp_INotifyHubClient_(_hubLifetimeManager_of_TestHub);
         }
 
     }
     // END: Microsoft_AspNetCore_SignalR_IHubContext_TestApp_TestHub_TestApp_INotifyHubClient__hubContext

this line, where it is declaring a func variable

private readonly Func<Microsoft.AspNetCore.SignalR.HubLifetimeManager<TestApp.TestHub>, Microsoft.AspNetCore.SignalR.IHubContext<TestApp.TestHub, TestApp.INotifyHubClient>> _func_of_HubLifetimeManager_TestApp_TestHub__IHubContext_TestApp_TestHub, TestApp_INotifyHubClient_; 

The variable name used includes a ","
func_of_HubLifetimeManager_TestApp_TestHub__IHubContext_TestApp_TestHub, TestApp_INotifyHubClient

I traced the problem to the Instance class, DefaultArgName method.
When I changed following line

argName += "_of_" + ServiceType.GetGenericArguments().Select(t => t.NameInCode().Replace("<", "_").Replace(">", "_").Replace(".", "_")).Join("_");

to also remove "," and empty spaces)

argName += "_of_" + ServiceType.GetGenericArguments().Select(t => t.NameInCode().Replace("<", "_").Replace(">", "_").Replace(".", "_").Replace(",", "_").Replace(" ", "_")).Join("_");

The test application stopped throwing the exception.

TestApp.zip

Support AutoFactory generation

Much, much later. I'm theorizing that the code generation should make this fairly simple and way more efficient than SM's version of the same, much less SM's old explicit argument feature

Ignore dynamic assemblies in call to ReferenceAssembly

Leads to some annoying output in test runs

System.NotSupportedException: The invoked member is not supported in a dynamic assembly.
   at System.Reflection.Emit.InternalAssemblyBuilder.get_Location()
   at Lamar.Compilation.AssemblyGenerator.ReferenceAssembly(Assembly assembly)
Could not make an assembly reference to DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null

Install-Package lamar pulls large amount of dependent packages in

Repro:

  1. WPF Project targeting .NET 4.7.2 (also tried with 4.7.1)
  2. Run install-package lamar

Expected Result:
Lamar is installed with its direct dependencies

Actual Result:

All(?) .NET Standard 2.0 Packages will be installed:

PM> install-package lamar -whatif
Attempting to gather dependency information for package 'lamar.1.0.2' with respect to project 'Contoso', targeting '.NETFramework,Version=v4.7.2'
Gathering dependency information took 3,46 sec
Attempting to resolve dependencies for package 'lamar.1.0.2' with DependencyBehavior 'Lowest'
Resolving dependency information took 0 ms
Resolving actions to install package 'lamar.1.0.2'
Resolved actions to install package 'lamar.1.0.2'
Install Microsoft.CodeAnalysis.Analyzers.1.1.0
Install Microsoft.Extensions.DependencyInjection.Abstractions.2.0.0
Install System.AppContext.4.3.0
Install System.Collections.4.3.0
Install System.Collections.Concurrent.4.3.0
Install System.Collections.Immutable.1.3.1
Install System.Composition.AttributedModel.1.0.31
Install System.Composition.Convention.1.0.31 : System.Composition.AttributedModel [1.0.31, )
Install System.Composition.Runtime.1.0.31
Install System.Composition.Hosting.1.0.31 : System.Composition.Runtime [1.0.31, )
Install System.Composition.TypedParts.1.0.31 : System.Composition.AttributedModel [1.0.31, ), System.Composition.Hosting [1.0.31, ), System.Composition.Runtime [1.0.31, )
Install System.Composition.1.0.31 : System.Composition.AttributedModel [1.0.31, ), System.Composition.Convention [1.0.31, ), System.Composition.Hosting [1.0.31, ), System.Composition.Runtime [1.0.31, ), System.Composition.TypedParts [1.0.31, )
Install System.Console.4.3.0
Install System.Diagnostics.Debug.4.3.0
Install System.Diagnostics.FileVersionInfo.4.3.0
Install System.Diagnostics.StackTrace.4.3.0
Install System.Diagnostics.Tools.4.3.0
Install System.Dynamic.Runtime.4.3.0
Install System.Globalization.4.3.0
Install System.IO.4.3.0
Install System.IO.Compression.4.3.0
Install System.IO.FileSystem.Primitives.4.3.0
Install System.IO.FileSystem.4.3.0 : System.IO.FileSystem.Primitives [4.3.0, )
Install System.Linq.4.3.0
Install System.Linq.Expressions.4.3.0
Install System.Reflection.4.3.0
Install System.Reflection.Extensions.4.3.0
Install System.Reflection.Metadata.1.4.2 : System.Collections.Immutable [1.3.1, )
Install System.Resources.ResourceManager.4.3.0
Install System.Runtime.4.3.0
Install System.Runtime.Extensions.4.3.0
Install System.Runtime.InteropServices.4.3.0 : System.Runtime [4.3.0, )
Install System.Runtime.Numerics.4.3.0
Install System.Security.Cryptography.Encoding.4.3.0
Install System.Security.Cryptography.Primitives.4.3.0
Install System.Security.Cryptography.Algorithms.4.3.0 : System.IO [4.3.0, ), System.Runtime [4.3.0, ), System.Security.Cryptography.Encoding [4.3.0, ), System.Security.Cryptography.Primitives [4.3.0, )
Install System.Security.Cryptography.X509Certificates.4.3.0 : System.Security.Cryptography.Algorithms [4.3.0, ), System.Security.Cryptography.Encoding [4.3.0, )
Install System.Text.Encoding.4.3.0
Install System.Text.Encoding.CodePages.4.3.0
Install System.Text.Encoding.Extensions.4.3.0
Install System.Threading.4.3.0
Install System.Threading.Tasks.4.3.0
Install System.Threading.Tasks.Parallel.4.3.0
Install System.Threading.Thread.4.3.0
Install System.ValueTuple.4.3.0
Install System.Xml.ReaderWriter.4.3.0
Install System.Xml.XDocument.4.3.0
Install System.Xml.XmlDocument.4.3.0
Install System.Xml.XPath.4.3.0
Install System.Xml.XPath.XDocument.4.3.0 : System.Xml.XPath [4.3.0, )
Install Microsoft.CodeAnalysis.Common.2.8.2 : Microsoft.CodeAnalysis.Analyzers [1.1.0, ), System.AppContext [4.3.0, ), System.Collections [4.3.0, ), System.Collections.Concurrent [4.3.0, ), System.Collections.Immutable [1.3.1, ), System.Console [4.3.0, ), System.Diagnostics.Debug [4.3.0, ), System.Diagnostics.FileVersionInfo [4.3.0, ), System.Diagnostics.StackTrace [4.3.0, ), System.Diagnostics.Tools [4.3.0, ), System.Dynamic.Runtime [4.3.0, ), System.Globalization [4.3.0, ), System.IO.Compression [4.3.0, ), System.IO.FileSystem [4.3.0, ), System.IO.FileSystem.Primitives [4.3.0, ), System.Linq [4.3.0, ), System.Linq.Expressions [4.3.0, ), System.Reflection [4.3.0, ), System.Reflection.Metadata [1.4.2, ), System.Resources.ResourceManager [4.3.0, ), System.Runtime [4.3.0, ), System.Runtime.Extensions [4.3.0, ), System.Runtime.InteropServices [4.3.0, ), System.Runtime.Numerics [4.3.0, ), System.Security.Cryptography.Algorithms [4.3.0, ), System.Security.Cryptography.Encoding [4.3.0, ), System.Security.Cryptography.X509Certificates [4.3.0, ), System.Text.Encoding [4.3.0, ), System.Text.Encoding.CodePages [4.3.0, ), System.Text.Encoding.Extensions [4.3.0, ), System.Threading [4.3.0, ), System.Threading.Tasks [4.3.0, ), System.Threading.Tasks.Parallel [4.3.0, ), System.Threading.Thread [4.3.0, ), System.ValueTuple [4.3.0, ), System.Xml.ReaderWriter [4.3.0, ), System.Xml.XDocument [4.3.0, ), System.Xml.XmlDocument [4.3.0, ), System.Xml.XPath.XDocument [4.3.0, )
Install Microsoft.CodeAnalysis.CSharp.2.8.2 : Microsoft.CodeAnalysis.Common [2.8.2, 2.8.2]
Install Microsoft.CodeAnalysis.Scripting.Common.2.8.2 : Microsoft.CodeAnalysis.Common [2.8.2, 2.8.2], System.AppContext [4.3.0, ), System.Collections [4.3.0, ), System.Collections.Immutable [1.3.1, ), System.Diagnostics.Debug [4.3.0, ), System.Diagnostics.StackTrace [4.3.0, ), System.Diagnostics.Tools [4.3.0, ), System.Globalization [4.3.0, ), System.IO [4.3.0, ), System.IO.FileSystem [4.3.0, ), System.Linq [4.3.0, ), System.Linq.Expressions [4.3.0, ), System.Reflection [4.3.0, ), System.Reflection.Extensions [4.3.0, ), System.Resources.ResourceManager [4.3.0, ), System.Runtime [4.3.0, ), System.Runtime.Extensions [4.3.0, ), System.Runtime.InteropServices [4.3.0, ), System.Threading [4.3.0, ), System.Threading.Tasks [4.3.0, )
Install Microsoft.CodeAnalysis.CSharp.Scripting.2.8.2 : Microsoft.CodeAnalysis.CSharp [2.8.2, 2.8.2], Microsoft.CodeAnalysis.Scripting.Common [2.8.2, 2.8.2]
Install Microsoft.CodeAnalysis.Scripting.2.8.2 : Microsoft.CodeAnalysis.CSharp.Scripting [2.8.2, 2.8.2], Microsoft.CodeAnalysis.Scripting.Common [2.8.2, 2.8.2]
Install Microsoft.CodeAnalysis.VisualBasic.2.8.2 : Microsoft.CodeAnalysis.Common [2.8.2, )
Install Microsoft.CodeAnalysis.Workspaces.Common.2.8.2 : Microsoft.CodeAnalysis.Common [2.8.2, 2.8.2], System.Composition [1.0.31, )
Install Microsoft.CodeAnalysis.CSharp.Workspaces.2.8.2 : Microsoft.CodeAnalysis.CSharp [2.8.2, 2.8.2], Microsoft.CodeAnalysis.Workspaces.Common [2.8.2, 2.8.2]
Install Microsoft.CodeAnalysis.VisualBasic.Workspaces.2.8.2 : Microsoft.CodeAnalysis.VisualBasic [2.8.2, 2.8.2], Microsoft.CodeAnalysis.Workspaces.Common [2.8.2, 2.8.2]
Install Microsoft.CodeAnalysis.2.8.2 : Microsoft.CodeAnalysis.CSharp.Workspaces [2.8.2, 2.8.2], Microsoft.CodeAnalysis.VisualBasic.Workspaces [2.8.2, 2.8.2]
Install Lamar.1.0.2 : Microsoft.CodeAnalysis [2.8.2, ), Microsoft.CodeAnalysis.CSharp [2.8.2, ), Microsoft.CodeAnalysis.Scripting [2.8.2, ), Microsoft.Extensions.DependencyInjection.Abstractions [2.0.0, )
Time Elapsed: 00:00:04.6767709

Injectable to accept Open Generics

Thanks for adding the Injectable system. The idea is sound, however I think it needs to accept open generics. MassTransit for example has both a ConsumerContext and a ConsumerContext<T>

I think we'd need to make Injectable allow the open type ConsumerContext<> and then be able to _.Inject(context) which may be a ConsumerContext<SomeClass> etc etc

This would need to be implemented using a Type object rather than Generic method I suppose?

serviceRegistry.Injectable(typeof(ConsumerContext<>))

I've had a look at implementing myself, but think I'd need to chat it through as I do it. So really am making this ticket as a reminder for either myself to attach it once I can get some gitter help, or if Jeremy knows the right way to implement this already?

Ambigious reference between IHostingEnvironment

When I try to use Lamar library with App.Metrics.AspNetCore.Mvc library in ASP.Net Core 2.1 application I got the following exception:

System.InvalidOperationException: Compilation failures!

CS0104: 'IHostingEnvironment' is an ambiguous reference between 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' and 'Microsoft.Extensions.Hosting.IHostingEnvironment'
CS0104: 'IApplicationLifetime' is an ambiguous reference between 'Microsoft.AspNetCore.Hosting.IApplicationLifetime' and 'Microsoft.Extensions.Hosting.IApplicationLifetime'

The code which is configured application:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseLamar()
            .UseMetrics()
            .UseStartup<Startup>();
}

Archive with solution to reproduce issue:
InvalidOperationExceptionOnStart.zip

Container.ForAsync() builder methods

Have a completely non-blocking async version to build out a Container object for an IServiceCollection, ServiceRegistry, or Action<ServiceRegistry> signature

Activation Interceptors

interception that just does something w/ a newly created object. Taking the terminology from SM

Randomize variable names in inline dependencies

Hitting a problem w/ two decorators that both used "inner" as the name of the constructor parameter, and the generated code blew up because the same variable name was used. It won't take long for creative users to hit this.

Adding migrations when using EF Core hangs

I am trying to create the migrations using the VS package managemer console's add-migration cmdlet as described here: https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db . With Lamar as my IoC container the cmdlet just hangs after writing out what looks like is some debugging info like:

[12:54:41 VRB] All Scanners
================================================================

No other output, and the only solution is to close visual studio and restart it.

Debugging dynamically generated and loaded assembly

Is there a way to debug the generated assembly from VS17? I am trying to execute the end_to_end_compilation.generate_dynamic_types_with_no_fields, generator.Generate(3, 4).

I have tried to extend LoadFromStream method with symbols as well, but with no success.

internal interface ILamarAssemblyLoadContext
{
Assembly LoadFromStream(Stream assembly, Stream symbols);
Assembly LoadFromAssemblyName(AssemblyName assemblyName);
Assembly LoadFromAssemblyPath(string assemblyName);
}

Retrofit UT's on Frame classes

They were all built in Jasper within integration tests, which was fine, but now they're in Blue w/o coverage.

  • NowFetchFrame
  • CompositeFrame
  • MethodCall
  • NoArgConstructor
  • CommentFrame
  • GeneratedMethod.DerivedVariables

"Warmup" command

The compilation is slooooooooooooooooow, so have a static method that returns Task somewhere that will create a fake assembly and discard it to warm up Roslyn.

Make it smart enough that you get Task.CompletedTask on subsequent calls

Decorators and generics

Is it possible to do the following yet. Or is there some other way to achieve this?

For(typeof(IFoo<,>)).DecorateAllWith(typeof(Bar<,>));

Overriding registry entry for certain interfaces

Hi,

Im not sure if I am missing this in the documentation anywhere but does Lamar support overriding how to resolve an instance by declaring it again later in the registry list?

We are currently migrating over from structuremap to Lamar and we currently scan an assembly then do any specific overrides. For example in structure map we would scan an assembly then do specific overrides for certain interfaces:

 var container = new Container(x =>
            {
                x.Scan(scan =>
                {
                    scan.AssemblyContainingType<IUnitOfWork>(); //get entire assembly dependancies    
                scan.WithDefaultConventions();               
                });
                x.For<IUnitOfWork>().Use(() => new UnitOfWork()); //override specific class
                
            });

In lamar, when I try this, I can see there is a second registry entry created and the latter does not get chosen. In the example below, the default registry is used, not the registry with the mocked out Unit of work.

 var x = new ServiceRegistry();

            x.Scan(scan =>
            {
                scan.AssemblyContainingType<IUnitOfWork>(); //get Carrier Integration
                scan.WithDefaultConventions();
            });

            //use a mocked out Unit of work instead of the real one in tests.
            x.For<IUnitOfWork>().Use(c => MockUow.Object);

Is there any way to do a scan then override particular interfaces with specific implementations? Do I need to somehow remove the scanned instance before I attempt to 'override' the interface?

NestedContainer affects parent container

If you override a type registration in a child container, this also affects the parent container:

using System;
using Lamar;
using Microsoft.Extensions.DependencyInjection;

namespace LamarTest
{
    public class Program
    {
        static void Main(string[] args)
        {
            var registry = new ServiceRegistry();
            registry.AddTransient<IService, DefaultService>();
            var container = new Container(registry);
            Resolve<DefaultService>(container);

            var nestedContainer = container.GetNestedContainer();
            nestedContainer.Configure(c => c.AddTransient<IService, NestedService>());
            Resolve<NestedService>(nestedContainer);

            // Wrong service is resolved from parent container
            Resolve<DefaultService>(container);
        }

        private static void Resolve<ExpectedType>(IContainer container)
        {
            var service = container.GetRequiredService<IService>();

            if (service is ExpectedType)
            {
                Console.WriteLine($"Expected type '{typeof(ExpectedType)}' was resolved");
            }
            else
            {
                Console.WriteLine($"Failure. Resolved '{service}' instead of '{typeof(ExpectedType)}'");
            }
        }
    }

    public interface IService
    {
    }

    public class DefaultService : IService
    {
    }

    public class NestedService : IService
    {
    }
}

ValueTuple variable usage has to be evaluated lazy

Create a MethodCall that returns a ValueTuple, then override the name of one of the variables within the tuple and generate code. Today it still uses the original name of the variable. Being a problem downstream in Jasper.

When resolving a handler from a HTTP request exception with message Unable to cast object of type 'Lamar.IoC.Scope' to type 'Lamar.IContainer'. is thrown

When trying to resolve a handler in a controller from a api request i get the message

Unable to cast object of type 'Lamar.IoC.Scope' to type 'Lamar.IContainer'.

This appears to be due to the registration written

this.For<ITableConnection>()
                .Use<TableConnection>().Ctor<string>().Is(c => c.GetInstance<IConfiguration>()["Storage:PrimaryConnectionString"]);

If I hard code the returned string the class resolves properly the TableConnection class takes a single string property

Runtime compilation failure due to protection level

I've got a new ASP.NET Core application where I'm trying to use Lamar (v0.9.4), and having some issues. Just to make sure it (probably) isn't my code, I changed to StructureMap and that worked just fine, so this seems to be Lamar-specific.

CS0122: 'AuthenticationBuilder.EnsureSignInScheme<TOptions>' is inaccessible due to its protection level

public override Microsoft.Extensions.Options.IPostConfigureOptions<Microsoft.AspNetCore.Authentication.Facebook.FacebookOptions> Build(Lamar.IoC.Scope scope)
{
     return new Microsoft.AspNetCore.Authentication.AuthenticationBuilder.EnsureSignInScheme<Microsoft.AspNetCore.Authentication.Facebook.FacebookOptions>(_options_of_AuthenticationOptions);
}

I can give you a complete solution if you want it, but you should be able to replicate it with the MVC starter template by adding Facebook authentication in ConfigureServices():

services.AddAuthentication().AddFacebook(facebookOptions =>
            {
                facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
                facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
            });

Null Ref in Lamar.IoC.Instances.CtorArg Constructor (due to optional parameters)

In Lamar.IoC.Instances.CtorArg(ParameterInfo parameter, Instance instance)
instance.ServiceType.IsGenericType

Based upon the code in ConstructorInstance.determineArgument, it appears that one should expect a null instance at this point. (ServiceGraph.FindDefault returns null)

Is there a missing null check or log in line 248 (determineArgument ) stating that we are missing a registration?
It would be nice to output the value of the Parameter in an error message from CtorArg Constructor to assist.

Or is the expectation that we should use the default value of the optional parameter as the instance. Even in this situation, I'd think a consumer would want to be warned we are falling back to the default value or no value when null is assigned.

To replicate:

public interface INotRegisteredParameter { }
public interface ISomeClass { }
public class SomeClass : ISomeClass
       {
           //This returns expected:  Lamar.IoC.LamarException  Cannot build registered instance
           //public SomeClass(INotRegisteredParameter parameter){}
           //Null Ref
           public SomeClass(INotRegisteredParameter parameter = null){}
       }

       [Fact]
       public void troubleshoot_constructor_OptionalArg_NullRef()
       {
           var container = new Container(services =>
           {
               services.AddSingleton<ISomeClass, SomeClass>();
           });

           var instance = container.GetInstance<ISomeClass>();
           instance.ShouldNotBeNull();
       }

WhatDoIHave() improvements

  • Need a "show me all details vertically" mode that can show all the details that get missed in the normal tabular display
  • Need a verbose mode that will show the generated code for anything
  • Query setting to ignore or include all system discovered instances like "list of all", "array of all", or "func for building". That'll do more than anything to improve the display.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.