Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property Injection in ASP.NET Core

I am trying to port an ASP.NET application to ASP.NET Core. I have property injection (using Ninject) on my UnitOfWork implementation like this:

[Inject] public IOrderRepository OrderRepository { get; set; } [Inject] public ICustomerRepository CustomerRepository { get; set; } 

Is there a way to achieve the same functionality using built-in DI on .NET Core? Also, is it possible to use convention-based binding?

like image 638
Özgür Kaplan Avatar asked Jul 19 '16 13:07

Özgür Kaplan


People also ask

Does .NET Core Support property injection?

ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies.

What is @inject in ASP.NET Core?

ASP.NET Core supports dependency injection into views. This can be useful for view-specific services, such as localization or data required only for populating view elements. Most of the data views display should be passed in from the controller. View or download sample code (how to download)

What is use of property injection?

In property injection, we need to pass object of the dependent class through a public property of the client class. Let's use the below example for the implementation of the Property Injection or even it is called Setter Injection as value or dependency getting set in property.

What is Property injection C#?

Property injection is a type of dependency injection where dependencies are provided through properties. Visit the Dependency Injection chapter to learn more about it. Let's understand how we can perform property injection using Unity container. Consider the following example classes. Example: C#


Video Answer


2 Answers

No, the built-in DI/IoC container is intentionally kept simple in both usage and features to offer a base for other DI containers to plug-in.

So there is no built-in support for: Auto-Discovery, Auto-Registrations, Decorators or Injectors, or convention based registrations. There are also no plans to add this to the built-in container yet as far as I know.

You'll have to use a third party container with property injection support.

Please note that property injection is considered bad in 98% of all scenarios, because it hides dependencies and there is no guarantee that the object will be injected when the class is created.

With constructor injection you can enforce this via constructor and check for null and the not create the instance of the class. With property injection this is impossible and during unit tests its not obvious which services/dependencies the class requires when they are not defined in the constructor, so easy to miss and get NullReferenceExceptions.

The only valid reason for Property Injection I ever found was to inject services into proxy classes generated by a third party library, i.e. WCF proxies created from an interface where you have no control about the object creation. And even there, its only for third party libraries. If you generate WCF Proxies yourself, you can easily extend the proxy class via partial class and add a new DI friendly constructor, methods or properties.

Avoid it everywhere else.

like image 158
Tseng Avatar answered Oct 06 '22 01:10

Tseng


Is there a way to achieve the same functionality using built-in DI on .NET Core?

No, but here is how you can create your own [inject] attributes with the help of Autofac's property injection mechanism.

First create your own InjectAttribute:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class InjectAttribute : Attribute {   public InjectAttribute() : base() { } } 

Then create your own InjectPropertySelector that uses reflection to check for properties marked with [inject]:

public class InjectPropertySelector : DefaultPropertySelector {   public InjectPropertySelector(bool preserveSetValues) : base(preserveSetValues)   { }    public override bool InjectProperty(PropertyInfo propertyInfo, object instance)   {     var attr = propertyInfo.GetCustomAttribute<InjectAttribute>(inherit: true);     return attr != null && propertyInfo.CanWrite             && (!PreserveSetValues             || (propertyInfo.CanRead && propertyInfo.GetValue(instance, null) == null));   } } 

Then use your selector in your ConfigureServices where you wire up your AutofacServiceProvider:

public class Startup {   public IServiceProvider ConfigureServices(IServiceCollection services)   {     var builder = new ContainerBuilder();     builder.Populate(services);          // use your property selector to discover the properties marked with [inject]     builder.RegisterType<MyServiceX>().PropertiesAutowired((new InjectablePropertySelector(true)););      this.ApplicationContainer = builder.Build();     return new AutofacServiceProvider(this.ApplicationContainer);   } } 

Finally in your service you can now use [inject]:

public class MyServiceX  {     [Inject]     public IOrderRepository OrderRepository { get; set; }     [Inject]     public ICustomerRepository CustomerRepository { get; set; } } 

You surely can take this solution even further, e.g. by using an attribute for specifying your service's lifecycle above your service's class definition...

[Injectable(LifetimeScope.SingleInstance)] public class IOrderRepository 

...and then checking for this attribute when configuring your services via Autofac. But this would go beyond the scope of this answer.

like image 43
B12Toaster Avatar answered Oct 06 '22 01:10

B12Toaster