Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register a internal class in unity?

How can you register an internal class from a different assembly, in a unity container?

UnityContainer container = new UnityContainer();
container.RegisterType<IPublicInterface, InternalClassImpl>(new ContainerControlledLifetimeManager());

Works great if InternalClassImpl is accessible outside it's assembly, but if it's internal, and implements IPublicInterface, the only real alternative seems to be offering a factory that can create them.

But If you have a factory creating the class, How can you continue to use Dependency Injection with Unity to inject it's dependencies?

Large Application

UnityContainer container = new UnityContainer();
container.RegisterType<IPublicInterface>(new InjectionFactory(c =>
InternalClassImplFactory.MakeInternalClassImpl()));

Small Library

namespace SmallLibrary
{
    public interface IPublicInterface
    {
    }

    public class InternalClassImplFactory
    {
        public static IPublicInterface MakeInternalClassImpl()
        {
            return new InternalClassImpl();
        }
    }

    internal class InternalClassImpl : IPublicInterface
    {
        public InternalClassImpl()
        {
        }
    }
}

But what happens if InternalClassImpl needs injected dependencies from Large Application and internal SmallLibrary Classes?

like image 411
Ryan Leach Avatar asked Aug 14 '26 01:08

Ryan Leach


1 Answers

You need UnityContainerExtension. Create new extension in library where internal class defined. Register your internal class in container.

public class Extension : UnityContainerExtension
{
    protected override void Initialize()
    {
        Container.RegisterType<IPublicInterface, InternalClassImpl>();
    }
}


public interface IPublicInterface
{
}

internal class InternalClassImpl : IPublicInterface
{
    public InternalClassImpl()
    {
    }
}

Now you can expose your implementation via the Extension. So, your implementation stays internal but you can use it.

static void Main(string[] args)
{
    var container = new UnityContainer();
    container.AddNewExtension<Extension>();
}
like image 106
Backs Avatar answered Aug 16 '26 23:08

Backs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!