Skip to content

Conversation

@jonah1nine
Copy link

Sometimes a concrete type could implement multiple interfaces and the instance of the concrete type needs to be registered against those interface.

Currently, we have the options below:

  1. AsImplementedInterfaces()
builder.RegisterInstance(instance).AsImplementedInterfaces();

Straightforward and neat! However, I try to avoid using this as it hides away registrations of types. My IDE can't help me find where a certain type is registered.

  1. Explicitly registering against the interfaces
builder.RegisterInstance<IInterfaceA, IInterfaceB, IInterfaceC>(instance);
// or
builder.RegisterInstance(instance)
    .As<IInterfaceA>()
    .As<IInterfaceB>()
    .As<IInterfaceC>();

Still relatively straightforward and neat! In addition, I can now easily see what the instance is registered against. My IDE can easily find these registrations.


Now, there are cases where it is not guaranteed that an instance implements a certain interface, but still needed to be registered if it is. Option 1 can handle this easily as it will only register against implemented interfaces. However, option 2 will fail and rightly throw an exception.

A way around this is to manually check the instance against the interfaces:

var registrationBuilder = builder.RegisterInstance(instance);

if (instance is IInterfaceA)
{
    registrationBuilder = registrationBuilder.As<IInterfaceA>();
}
if (instance is IInterfaceB)
{
    registrationBuilder = registrationBuilder.As<IInterfaceB>();
}
if (instance is IInterfaceC)
{
    registrationBuilder.As<IInterfaceC>();
}

This is cumbersome the more interfaces you need to check against.


This PR adds a new version of As that doesn't throw an exception if the instance does not implement the interface it's being registered against: TryAs

With this, we can write above similar to option 2:

builder.RegisterInstance(instance)
   .TryAs<IInterfaceA>()
   .TryAs<IInterfaceB>()
   .TryAs<IInterfaceC>();

Back to straightforward and neat!

Note: I went for a very simple implementation and just added a boolean flag to the AddInterfaceType method. Feel free to come up with a better implementation.

@vercel
Copy link

vercel bot commented Jun 12, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
vcontainer ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 12, 2025 11:51am

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant