Search code examples
c#.netdependency-injectionunity-container

How to resolve concrete non abstract class instance


I have following issue. I have abstract base type and concrete subtype

    public interface IInterface
    {
        void SomeAction()
    }

    public class CClass : IInterface
    {
        public void SomeAction()
        {
            throw new NotImplementedException();
        }
    }

I would like resolve interface dependensies using factory method but sometimes i would like resolve concrete class dependensies without factory method. I mean:

    container.RegisterType<IInterface, CClass>(new InjectionFactory(FactoryMethod));

My factory method is:

    private object FactoryMethod(IUnityContainer arg)
    {
        /* do some specific logic */
        return new CClass();
    } 

Some times i would like resolve it using factory method:

var c1 = container.Resolve<IInterface>();

But sometimes I would like resove it without FactoryMethod call

var c2 = container.Resolve<CClass>();

But FactoryMethod is called every way. Why? What is wrong? I want use factory method for abstract dependensies olnly


Solution

  • To resolve a concrete class you don't need to register it. Unity will try to create the instance.

    To resolve the interface using factory method you need to register only the interface as showed in your answer:

    container.RegisterType<IInterface>(new InjectionFactory(FactoryMethod));
    

    And there is no bad practice here.

    BTW, your initial interface registration container.RegisterType<IInterface, CClass>(new InjectionFactory(FactoryMethod)) gives me System.InvalidOperationException. Whatever it is, I don't see any reason to specify the second generic parameter in that case.