r/dotnet • • 5d ago

Promotion Injectify v1.0 attribute-based service registration for Microsoft.Extensions.DependencyInjection

Post image

Hi r/dotnet,

I've been working on a small .NET library called Injectify. It's now at version 1.0.5 on NuGet, and this is the first time I'm sharing it here.

The idea came from wanting to reduce the repetitive dependency registration code that often accumulates in Program.cs (AddScoped, AddSingleton, AddTransient, etc.).

With Injectify, you can declare service lifetimes directly on classes using attributes like [Scoped], [Singleton], and [Transient], then register everything from an assembly with a single call.

It also includes DrawAggregator, which generates Mermaid dependency graphs from annotated classes, making it easier to visualize constructor dependencies.

The library is lightweight and has no external dependencies.

GitHub: https://github.com/Roma1011/Injectify

NuGet: https://www.nuget.org/packages/Injectify.Auto

I'd love to hear your feedback. Would you consider using attribute-based DI registration in your projects, or do you prefer keeping registrations explicit in Program.cs?

Thanks!

17 Upvotes

40 comments sorted by

113

u/daltorak 5d ago edited 5d ago

With all due love and affection, and with respect for the time you've put in...... man, this isn't the way.

Jeremy Miller invented this concept in Structuremap like 20 years ago.... and I was one of the first people to use it, so I saw all this unfold in real time. He eventually realized that there is a major flaw with attribute-based registration: It forces your domain to have a dependency on your DI library, which it absolutely should not have.... DI containers are an infrastructure concern, not an application concern. Also, application may want different instantiation behaviours under different conditions, and these become really difficult to express as attributes when simple code is easier to write and comprehend.

That's actually why Microsoft chose to not implement attributes when they introduced their first-party DI container. It's not an oversight that was waiting for someone to come along and fix, it is extremely intentional so that developers wouldn't footgun themselves.

It's the same story with the old DataAnnotations class and related attributes [Range], [Required] and all that. Microsoft introduced that model way back in the day, then realized after a few years that it created more problems than it solved, so their recommendations moved away from annotating properties with validations, and towards external validator functions. Again, its separation of concerns: A plain C# class at the core of your domain model shouldn't need to know how to generate localized error text -- which is an application-level concern, not domain model level.

In more recent times, another practical reason has emerged for why assembly scanning isn't the way: It doesn't work well with Native AOT, because types that aren't referenced anywhere (including attributes) are stripped from the final output. If someone is stringing together their classes using interfaces, and there's no line of code somewhere that connects it to a concrete class, then that concrete classes end up having no references, and poof!

7

u/Inevitable-Draft-971 5d ago

Thanks, this is really useful context. I didn’t know the StructureMap history.

I agree with the main point: the domain shouldn’t know about the DI library. Right now it’s actually worse than it needs to be, because the interface also needs the attribute, and interfaces often live in the domain. That’s the first thing I want to change: the attribute only on the implementation, which usually lives in the infrastructure/application layer. Then the domain project wouldn’t reference Injectify at all.

For conditional or factory-based registrations I agree, code is better, and Injectify isn’t trying to replace that. It’s for the plain “this class is scoped” cases, and you register the rest by hand next to it.

On DataAnnotations, I’m not sure Microsoft moved away from them. .NET 8 added new ones (Length, AllowedValues) and .NET 10’s built-in Minimal API validation is based on them. But I get the separation of concerns argument.

0

u/MSgtGunny 5d ago

I think if you created an export function that migrated the attribute based DI to a program.cs based di registration (and maybe vice versa), you’d have something handy for small projects that’s easy to convert into the more proper form if and when the project grows.

9

u/skennaly 5d ago

yeah the point about polluting the domain layer with infrastructure concerns is really the biggest issue with this pattern imo.

4

u/tim128 5d ago

A plain C# class at the core of your domain model shouldn't need to know how to generate localized error text -- which is an application-level concern, not domain model level.

You shouldn't attempt this in the first place. The API/view layer is indeed a separate concern. They should already be separate models.

3

u/FullPoet 5d ago

Structuremap like 20 years ago

fugg im old

1

u/WellHydrated 5d ago

>DI containers are an infrastructure concern, not an application concern.

This is highly unlikely to matter in a standard web API.

1

u/StrangeWill 4d ago

It's mostly useful as a transitionary thing as you add di to a project that hasn't had it before 

And then you rip all that shit out when you're done

1

u/hevilhuy 5d ago

Most of the time the services are only injected in 1 project, so the approach is fine.
Even the services are injected in 2 or projects, changing their life time could uninteded changes it's business logic so I would avoid register them over again.
However, there is a mature library which do this without the reflection but source generator. Not only that, the library also support gRPC services.
Check out Roar.DependencyInjection.
NuGet: https://www.nuget.org/packages/Roar.DependencyInjection
GutHub: https://github.com/Blazor-School/roar-dependency-injection

30

u/philip_laureano 5d ago

As someone that was there since .NET 1.0 and when IOC containers were in their infancy: those who do not study history are doomed to repeat it.

-1

u/Inevitable-Draft-971 5d ago

Almost 25 years. That's seriously impressive! 👏

24

u/Impressive-Desk2576 5d ago

Oh boy, not another one. You do not understand the purpose of DI.

-9

u/Inevitable-Draft-971 5d ago

I’m not sure what your understanding of DI is, but it’s broader than just the .NET approach.

Think of it in terms of mathematical mappings between sets: abstractions (A) and implementations (B).
DI establishes relationships between these sets, then resolves those relationships when needed.

Of course, DI goes beyond mapping, but that’s a fundamental part of it. How you choose to implement that mapping is a matter of design preference and architectural trade-offs.

7

u/Impressive-Desk2576 5d ago edited 5d ago

The main purpose is to reduce the coupling between classes. Combined with a composition root you get a system where the dirty implementation details are at the outer rim of your system and contained in one place. This library and all the ones before them destroy both of these advantages. The details are spread over the code and it reintroduce coupling. Its pure utter nonsense.

8

u/Kanegou 5d ago

No. I would not use it. It's not even about preference. Attribute based registration simply doesn't not work if you need more advanced registrations like custom factory methods. Besides, having a dependency on anything di related inside your interfaces and implementations is a code smell in my opinion.

1

u/Inevitable-Draft-971 5d ago

AOP is another good example. Attributes and annotations are widely used in Aspect-Oriented Programming to declare cross-cutting concerns like logging, caching, and transactions, which frameworks handle automatically.

Injectify follows a similar declarative approach: describe the intent through metadata and let the framework handle the infrastructure.

-11

u/Kanegou 5d ago

Yes. I know. I probably know more about aspect oriented programming then you do ;)

2

u/david_fire_vollie 5d ago

"than", not "then".

1

u/Inevitable-Draft-971 5d ago

Fair points, and yes, it’s a design decision. It’s not meant to replace manual registration.

Factory methods stay in Program.cs. AggregateLifeTime is just an extension on IServiceCollection, so both work together:

builder.Services.AggregateLifeTime(typeof(Program).Assembly);
builder.Services.AddSingleton<IConnectionMultiplexer>(_ =>
    ConnectionMultiplexer.Connect(builder.Configuration.GetConnectionString("Redis")!));

Spring works the same way: u/Service / u/Component with component scanning for the simple cases, and u/Bean methods in a u/Configuration class when you need a factory.

On the code smell part, I get it. Your classes do reference the attributes. But it’s the same trade-off as Spring’s u/Service or Jakarta CDI’s u/ApplicationScoped / u/RequestScoped, which map pretty much 1:1 to Singleton / Scoped. Even Microsoft puts [FromKeyedServices] on constructor parameters since .NET 8. If you want your domain project completely free of DI references, this library probably isn’t for you, and that’s fine.

4

u/Kanegou 5d ago

Id rather have all my registrations in the same place or using the same methods. Instead of having some attribute based and some with explicit registrations.

2

u/Discipline_Cautious1 5d ago

Why do you need it on both interface and implementation?

Is it Keyed dependency injection?

1

u/Inevitable-Draft-971 5d ago

No, it's not keyed DI. Everything is registered through the standard DI container, just like AddScoped<IFoo, Foo>(). Keyed services aren't supported yet.

The attribute on the implementation defines the service lifetime, while the attribute on the interface tells Injectify which interface the implementation should be registered against.

This is particularly useful when a class implements multiple interfaces (e.g. IDisposable), so Injectify knows which one to use. If no matching interface is found, the class is registered as itself.

You're right about the redundancy, though. Having to declare the same lifetime twice isn't ideal.

I'm considering simplifying this in a future version by automatically matching interfaces by name (e.g. OrderService → IOrderService) or allowing an explicit interface reference in the attribute.

1

u/chucker23n 5d ago

while the attribute on the interface tells Injectify which interface the implementation should be registered against.

But the interface shouldn’t know anything about its implementations. That’s the whole point.

2

u/jakubiszon 5d ago

And what if an interface comes from a nuget?

11

u/anina_jessika 5d ago

i'd keep registrations explicit in program.cs. attributes on the classes hide where the wiring actually happens

1

u/Responsible-Cold-627 5d ago

Does it use runtime reflection, or source generators? I would check myself, but github got taken over by unicorns again.

2

u/Inevitable-Draft-971 5d ago

Runtime reflection. AggregateLifeTime scans the assembly once at startup and adds normal ServiceDescriptors to the IServiceCollection. After that it’s just Microsoft’s container, Injectify isn’t involved in resolving anything.

Roughly what it does:

foreach (var type in assembly.GetTypes())
{
    // only concrete classes with [Singleton], [Scoped] or [Transient]
    // service type = first interface with the same attribute, otherwise the class itself
    services.Add(new ServiceDescriptor(serviceType, type, lifetime));
}

So [Scoped] on OrderService and IOrderService gives you the same descriptor as AddScoped<IOrderService, OrderService>().

Because of the reflection it’s not AOT/trimming friendly right now. A source generator is something I’m looking at for a future version.

2

u/tanczosm 5d ago

https://github.com/loresoft/Injectio

Here an implementation that is a little more feature complete and doesn't rely on reflection.

You got a lot of really good advice on why you wouldn't want to do something like this anyway. I personally never found dependency injection to be the most headache prone part of development but that's just me. I don't think it's an actual pain point and at any sufficient level of complexity I think you would be surprised to learn that you are making it one with this library.

Like.. it's a one to one swap.. you are removing a well understood DI registration step and replacing it with an attribute.

0

u/Inevitable-Draft-971 5d ago

Haha, thanks for the reference! Always good to discover another DI library.

I agree, DI isn't rocket science, and I'm definitely not trying to reinvent the wheel here. I just wanted to scratch my own itch and see if I could make the repetitive parts a little less repetitive. 😄

Also, Injectify comes with DrawAggregator for Mermaid dependency graph generation, so there's a little more to it than just swapping registrations for attributes.

Not every tool needs to be for everyone. Appreciate you taking the time to share your thoughts!

1

u/harrison_314 5d ago

As many others have mentioned, using attributes is not the right approach. I would also recommend this page, which explains the design decisions behind Simple Injector - in my view, it is the best DI container from an architectural standpoint. I used it back in the full .NET Framework days.

The article explains why Simple Injector avoids certain practices, saving you from having to explore dead ends yourself.

https://docs.simpleinjector.org/en/latest/decisions.html

1

u/Inevitable-Draft-971 5d ago

Thanks! That's actually one of my favorite articles, and Simple Injector is a great DI container. I'm well aware of the trade-offs.

For me, it's about balancing architectural principles with developer productivity. Keeping DI concerns separate makes sense, but I also think we should avoid unnecessary boilerplate when a simpler approach can achieve the same result.

EF Core is a good example: it supports both attributes and the Fluent API. You can use attributes for straightforward cases and the Fluent API when you need more control.

That's exactly what I'm aiming for with Injectify. Keep explicit registration for factories, decorators, and conditional logic, while automating the repetitive cases. Both approaches can coexist.

1

u/harrison_314 5d ago

To be honest, in EF Core I’ve always used only the Fluent API—precisely because projects grow, and this way I have the configuration in just one place instead of having to hunt for it across various entities.

2

u/Liberal_Mormon 5d ago

I will mention, I use a library for service registration via attributes... But it uses those attributes for code generation, and then you use the generated code to register your services in a single method per assembly. This gets around a lot of the pitfalls of pure-attribute registration

If you are curious, it is baked into FastEndpoints.

2

u/hevilhuy 5d ago edited 5d ago

There is an exact same library, but not with reflection. Roar.DependecyInjection is a source-generstor with attrbites like ScopedService, TransientService, SingletonService. It's also support gRPC. NuGet: https://www.nuget.org/packages/Roar.DependencyInjection GitHub: https://github.com/Blazor-School/roar-dependency-injection

2

u/One_Web_7940 5d ago

But why ? 

1

u/AutoModerator 5d ago

Thanks for your post Inevitable-Draft-971. Please note that we don't allow spam, and we ask that you follow the rules available in the sidebar. We have a lot of commonly asked questions so if this post gets removed, please do a search and see if it's already been asked.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/vORP 5d ago

The Angular side of me says, "Oh, cool!"

The .NET side of me, however, thinks this is a bad idea - there are a lot of good reasons already shared on this thread, but aside from all of those... attributes would be a pain to manage in a large app at scale like this, and I would not want to go hunting for poorly decided scope lifetimes if I needed to make changes

1

u/Throwaway-_-Anxiety 5d ago

Doesn't spring boot on the java side do the same thing? What makes it hard to manage here compared to there?