I want to inject instances of services from my IoC-container of choice into the constructor of a markup extension. Is there a safe way to hook it up?
I use Microsoft.Extensions.DependencyInjection as an abstraction.
Now I see that MarkupExtensions are required to have a parameterless constructor.
And that the IServiceProvider that gets passed into the ProvideValue method only resolves XAML services.
In my case I have a TranslateExtension with a dependency on a ResourceContainer service which is currently being resolved by a Service Locator (a bad pattern). I would rather inject the ResourceContainer in the constructor.
Anyway, it would be useful to be able to inject anything anywhere in Xamarin.Forms.
I suggest building an infrastructure based around a common abstraction layer that supports multiple provider, such as Microsoft.Extensions.DependencyInjection.
@AmrAlSayed0 Yes. I've done some more experimentation, and I got it working with ResolveUsing. However, it does not work for MarkupExtensions. A parameterless constructor is required to activate the class.
@robertsundstrom Sorry I deleted my comment after realizing I was wrong. You are right, MarkupExtensions still use Activator.CreateInstance for resolving. https://github.com/xamarin/Xamarin.Forms/blob/e3b6e4755eda0e7611694929d6b0529ee2c40d4b/Xamarin.Forms.Xaml/MarkupExtensionParser.cs#L38
Hello,
I found Prism (with Unity DI container or others) more useful than that of DependencyService in Xamarin because it supports applying IoC principles such as constructor injection. Though, the current built in one is productive, it would be nice if it had a capability of doing such things. I felt the essence of this because it provides a number of flexibility including loosely coupling, test-ability and so on. I can use prism with unity or anything else, but I (and probably other developers in the community out there) would love Xamarin more than ever before if such functionality is incorporated in Xamarin by default because there might be someone out there like me who don't want to rely on third-party libraries rather they rely on Xamarin itself. Additionally it would be great if it has such functionality to integrate with third party libraries for DI containers only like the DI container .NET Core uses by default in ASP.NET Core project.
Thanks in advance.
markup extensions can't have ctor parameters injected. but you can use property injection, that ends up being similar at the end (a ctor parameter is no more than a property being set, with some guarantee of timing)