How can I auto resolve concrete types in Lamar?

449 Views Asked by At

The following documentation is not working for multiple reasons:

https://jasperfx.github.io/lamar/documentation/ioc/resolving/requesting-a-concrete-type/

First the documentation states that you can new up a Container with a default constructor which is not true. Secondly the following is not working for me.

var container = new Container(registry => { });
var testClass = container.GetInstance<TestClass>();

public class TestClass {}

Here's the error and stack trace from

var testClass = container.GetInstance<TestClass>();

Lamar.IoC.LamarMissingRegistrationException : No service registrations exist or can be derived for netcore.tests.web.UnitTests.ExtensionMethods.IServiceCollectionExtensionsTests.When_creating_a_new_instance_after_applying_the_AddTransientForAll_rule.TestClass at Lamar.IoC.Scope.GetInstance(Type serviceType) at Lamar.IoC.Scope.GetInstanceT at netcore.tests.web.UnitTests.ExtensionMethods.IServiceCollectionExtensionsTests.When_creating_a_new_instance_after_applying_the_AddTransientForAll_rule..ctor()

Any suggestions on how to get concrete types to auto resolve would be appreciated.

2

There are 2 best solutions below

5
Nkosi On

Based on the source code, things have changed since that documentation.

Try using the constructor that takes a service collection

var services = new ServiceCollection();
var container = new Container(services);
var testClass = container.GetInstance<TestClass>();
2
mxmissile On

I got this to work, was bugging me all night:

using Lamar;

namespace ConsoleApp2
{
    public class TestClass {}

    class Program
    {
        static void Main(string[] args)
        {
            var container = new Container(_ => { });

            var testClass = container.GetInstance<TestClass>();
        }
    }
}

This does not work:

class Program
{
    static void Main(string[] args)
    {
        var container = new Container(_ => { });

        var testClass = container.GetInstance<TestClass>();
    }

    public class TestClass {}
}