The best way to add injection
tossnet opened this issue · 8 comments
I always wonder where to put my injections...
- in the RAZOR page (@Inject ...)
- in the partial class ([injec] ...
What is your opinion?
In my opinion, I prefer to put all the code in the "Code Behind" file.
And therefore, to put the injection in the .cs.
The .razor is only used for the design part and the layout of this HTML design (via loops and Razor tests)
Do you inject in private or public properties?
private Factory Factory { get; set; }
public Factory Factory { get; set; }
in my case, all in private
So, a best practice will be
[Inject]
private IMemoryCache MemoryCache { get; set; }
In my best practices, all attributes are above of the property/method... so, including [Inject]
The first reason is, because you can have multiple attributes : serialization, authorizations, decoration, injection, ...
It's for this reason, I'm using a Factory pattern to include all service references into a Factory class.
So, in my component / page, when I need to use a service of my project, I inject Factory
and I use the property Factory.Profiles
.
Factory class
public virtual ProfileService Profiles => _profileService ?? (_profileService = new ProfileService(this));
public virtual AccountingService Accounting => _accountingService ?? (_accountingService = new AccountingService(this));
If the service is provided my Microsoft or external library, I inject the service directly to my component.
The Factory is used only for my services.