Prism Xamarin.Forms dependency injection constructor parameters - xamarin.forms

I'm using Xamarin.Forms with Prism. I'm using the Dependency Injection provided by prism. (also to inject instances of my own classes, not only platform specific)
My question is how can I pass parameters to the constructor in Dependency Injection?
Thanks

You normally don't pass parameters via a ctor. You only inject your class dependencies such as services. To inject your services just register them with the container in the RegisterTypes method in the App.cs
Assuming you are using Unity:
Container.RegisterType<IMyService, MyService>(optionally make it a singleton)

Related

Implement mapster dependency injection via Simple Injector IoC container

I'm using Mapster for mapping and Simple Injector in my .net framework 4.8 MVC and WebApi controllers.
I'd like to inject Mapster as a dependency in my services but I can't figure it out how to make it work with Simple Injector. The Mapster documentation is really vague in my opinion:
Mapster - Dependency Injection
Mapster - References
Can someone provide and example of how to use Mapster with Simple Injector? Doesn't matter if the controller is mvc or a web api.
The code I need is the configuration in Application_Start in Global.asax.cs and in the service concrete. Thanks!
I'm unfamiliar with Mapster, but after looking at the documentation link you provided, I'm assuming that integrating with Simple Injector can be done as follows:
var config = new TypeAdapterConfig();
container.RegisterInstance(config);
services.RegisterSingleton<IMapper, SimpleInjectorMapper>();
Where SimpleInjectorMapper is:
public sealed class SimpleInjectorMapper : ServiceMapper
{
public SimpleInjectorMapper(
Container container, TypeAdapterConfig config)
: base(container, config)
{
}
}
The 'trick' here is that the Simple Injector Container class implements System.IServiceProvider, which is the base interface used by most of the DI facilities in .NET and .NET Core and is the base interface that the MS.DI abstraction relies on. Mapsters ServiceMapper expects an IServiceProvider in its constructor, which is now provided using the Container.
There are a few downsides to this approach. Main downside is that in case a dependency is missing, you'll get a more generic "no service registered" exception in line with what MS.DI would throw, instead of a very information rich exception that Simple Injector would throw in case the resolve would fail when you call Container.GetInstance.
This, however, is a as far as I can go in providing an answer. If you wish to integrate more deeply with Simple Injector, you likely need a more complex SimpleInjectorMapper implementation, but others (e.g. the designers behind Mapster) need to help you with that. At least, hopefully, this answer will get you started.

Unity DI - C# Dependency Injection how to use with a repository class constructor ? It's only intended for controllers?

i wanna know if it's possible to inject dependency for a class constructor as it is injected for controllers, i have the following cenario as an example:
An AccountController which depends on an AccountRepository like bellow:
public AccountController(IAccountRepository repository)
The dependency is injected perfectly using Unity DI, which have the following configuration:
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager(), accountInjectionConstructor);
container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<IdentityDbContext<ApplicationUser>, ApplicationDbContext>(new HierarchicalLifetimeManager());
The problem is that i have a class AuthorizationServiceProvider which also needs the AccountRepository... In this case, how would i instantiate or use this AuthorizationServiceProvider class without having to instantiate and provide it all the dependencies?
Provider = new SimpleAuthorizationServerProvider>(),
This provider is set inside the Startup class and called before the Unity DI config initializes...
Here the visual studio complains that there's no argument given that corresponds to the class constructor, but if i provide a new AccountRepository i'd have to provide all it's dependencies as well, (ApplicationDbContext context, UserManager userManager) which are already provided for the Unity DI when creating the controllers....
Could somebody help me please?
Thanks in advance...
how would i instantiate or use this AuthorizationServiceProvider class without having to instantiate and provide it all the dependencies?
You can't. This is actually the core of what we're trying to achieve with Dependency Injection. Your application code should let go of the control over its dependencies. This means that your application code should not create an AuthorizationServiceProvider. Rather, it should let a third-party provide this dependency. Typically, this means you require the dependency be supplied using Constructor Injection.
Letting application code create these dependencies itself causes problems, typically referred to as the Control Freak anti-pattern or Dependency Inversion Principle violation. It causes strong coupling, which can hinder maintainability.
When working with Dependency Injection, this third-party is called the Composition Root. The Composition Root is:
a (preferably) unique location in an application where modules are composed together.
With DI, only the Composition Root will create graphs of objects. You are using Unity, which is a DI Container. The DI Container acts as the Composer, which is part of your Composition Root.
Instead of using a DI Container, you can build the object graphs by hand, which means you will have to create a complete tree of dependencies at once. This practice is called Pure DI. Still, the Composition Root is the location where those object graphs are created; with or without a DI Container.
Your view of DI might be troubled by the use of the standard Identity template that Visual Studio provides. From a design and DI perspective, however, this template is horrifying.
Either way, all these stated concepts, patterns and anti-patterns are described quite thoroughly in the book Dependency Injection in .NET by Mark Seemann.

StructureMap and classes that cannot accept constructor arguments

I have a ASP.NET web application (not MVC) which is actually a CMS application. I'm trying to set up StructureMap IoC framework and it's working well, but I've now hit a blocker in my understanding.
In my understanding, StructureMap enforces a pattern where all dependencies are registered in the core application assembly, so underlying assemblies do not themselves have a dependency on StructureMap.
So, say my application is My.App and it references another assembly My.Logic. My dependencies are all registered in a Container in My.App. This means that a class in My.Logic can take injected dependencies using a constructor like this:
public class Foo
{
private readonly IBar bar;
public Foo(IBar bar)
{
this.bar = bar;
}
}
But now I have a case where my class in My.Logic is a type which must be registered in the CMS, and this requires that it has an empty constructor.
So the problem is, if I can't inject using constructor parameters, and My.Logic doesn't have a dependency on My.App so I don't have access to the IoC container, is it possible to use StructureMap to handle this scenario?
If not, what alternative do I have other than create the class within the same assembly as the IoC container?
Use setter injection. See here
For<IBar>().Use<MyBar>();
Policies.FillAllPropertiesOfType<IBar>();

Does Unity have Autofac's equivilent of Owned<> to force new instance to be created

The project I'm on requires we use Unity. The lifetime managers are correctly set so this is not an issue with setting a lifetime manager. We have a special case where I need to resolve a service but it needs to freshly resolve every dependency as if it was the original request. In Autofac I can do this by injecting an Owned. Does Unity support anything like that or is there a way I can call Resolve and get a fresh set of injections?
Unity doesn't have equivalent of Autofac's Owned<> feature.
As for your problem, I think factories could solve it. You can write your own factory or use Unity Automatic Factories feature. More info on msdn.
I ended up using a Marker interface and registering that interface with a different scope. Then when I must have a new instance and not a shared instance I use the other interface.

Using Microsoft Unity 2.0 framework with a web application

When using Unity 2.0 for dependency injection within a web application, it appears that user controls, pages, etc will all need make explicit calls to retrieve the container and "fetch" the dependencies … so using the annotations like [dependency] won't offer any value. This is likely since the location of the container (application context, http context cache, etc.) is unknown in the web configuration.
Since Unity itself provides method interception, isn't there a way to "tell" unity how to fetch the container correctly when you build your own web application? Rather than having to create base classes for page, etc.?
The problem is that the WebForms Pages and Controls are not set up to allow for construction by dependency injection, so Unity never gets invoked at all unless the class invokes Unity itself. I've found the best pattern in these cases is to invoke the DI framework in the constructor via a Service Locator and then use annotations to mark dependency properties. Something like this:
public MyPage()
{
// Injector is a wrapper class so you can change the underlying DI framework
// later if necessary.
Injector.Inject(this);
}
[Dependency]
public SomeService MyService {get;set;}

Resources