How to provide capability like OnActivate (in Autofac) in Mvx.IoCProvider.Register - reflection

Autofac provides the OnActivated() method, which provides the capability to run any action after constructing a registered type.
Is possible to use a similar method in MvvmCross? Do you have any ideas to provide the same functionality?

It usually pays to understand the fundamentals of Dependency Injection (DI) instead of relying on particular DI Container features. Ask yourself the question: If I didn't have a DI Container, then how would I solve my problem?
Ironically, it turns out that things are usually much simpler with Pure DI.
If you didn't have a DI Container, then how would you run an action after construction of an object?
The easiest solution is to provide a factory that creates and initialises the object. Assuming the same API and requirements as the Autofac documentation implies, you could do this:
public static Dependency2 CreateDependency2(ITestOutputHelper output, Dependency1 dependency)
{
var d2 = new Dependency2(ITestOutputHelper output, Dependency1 dependency);
d2.Initialize();
return d2;
}
If you still must use another DI Container, most of them enable you to register a factory like the above against the type. I don't know how MvvmCross works, but I'd be surprised if this wasn't possible. If it isn't, you can implement an Adapter over your actual dependency. The Adapter would take care of running the action on the adapted object.
FWIW, if an object isn't in a valid state before you've run some action on it, then encapsulation is broken. The fundamental characteristic of encapsulation is that objects protect their invariants so that they can never be in invalid states. If possible, consider a better API design.

Related

Dependency injection using PRISM Xamarin Forms doesn't work

I have a problem with dependency injection in my project. I use PRISM framework in my project and I chose Ioc container when create it. Link -> https://github.com/blackpantific/InstagroomEX
In my app.xaml file I associate the class and interface
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation();
containerRegistry.RegisterForNavigation<WelcomeView, WelcomeViewModel>();
containerRegistry.RegisterForNavigation<RegistrationView, RegistrationViewModel>();
containerRegistry.RegisterForNavigation<LoginView, LoginViewModel>();
//regestering
containerRegistry.RegisterSingleton<IValidationService, ValidationService>();
}
But my page after initializing() doesn't appear at the screen. This is ViewModel constructor
public RegistrationViewModel(INavigationService navigationService, IUserDataService userDataService,
IValidationService validationService) :
base(navigationService)
{
_userDataService = userDataService;
_validationService = validationService;
}
Something wrong here. When I pass to the RegistrationViewModel() constructor another parameters besides INavigationService navigationService the RegistrationView page doesn't not displayed. What am I doing wrong?
Assuming that WelcomePage is displayed correctly and RegistrationPage is not, I think that Andres Castro is correct: Prism tries to resolve the IUserDataService which is not possible. In the debug output you should see a message that IUserDataService cannot be resolved.
(Note: The following is based on my experiences with Prism and Unity. This might hold for other Dependency Injection frameworks, but it's possible that other frameworks behave differently.)
Prism relies on a Dependency Injection (DI) framework, for example Microsofts Unity application block. What happens when you try to navigate to RegistrationPage is, that Prism (if you are using ViewModelLocator.AutowireViewModel="True") tries to determine the type of the viewmodel (by convention) and asks the underlying DI framework to resolve this type (i.e. create an instance). For each of the required constructors parameters of this type, then again the DI framework tries to resolve them. If the parameters require concrete types it will then try to resolve those. If the parametery require interface (or abstract) types, the DI framework will look at its registrations and if the types have been registered create instances according to this registrations (which in turn might involve resolving other types).
If - however - the parameter requires an interface type which has not been registered, the DI framework does not know how to handle the situation. It coulld of course assume null, but this might lead to errors that might be way harder to track down, hence it will throw an exception (which is swallowed and Logged by Prism).
Now how can you handle the situation?
You'll need to tell the DI framework how to resolve IUserDataInterface. Since RegistrationPageViewModel does not actually use it, you could register null
containerRegistry.RegisterInstance<IValidationService>(null);
Could be irritating later, though. I'd rather remove the dependency of RegistrationPageViewModel to IUserDataService altogether - for now and add it later when it's actually used - or create a mock/stub that implements IUserDataService and is used as long there is no real implementation. This would be registered with the DI framework as you did with IValidationService.

ASP.Net MVC 6: Recursive Dependency Injection

Still exploring the new ASP.NET MVC5, now with build in DI!
No Problem so far, I can just inject my Handlers (I don't like the Term Service, since this defines to me a Platform-Neutral Interface):
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.Configure<Model.Meta.AppSettings>(Configuration.GetSection("AppSettings"));
services.AddSingleton(typeof(Logic.UserEndPointConfigurationHandler));
services.AddSingleton(typeof(Logic.NetworkHandler));
services.AddMvc();
}
Works fine, also the strongly typed Configuration-Object "AppSettings" works perfectly fine.
Also the Injection in the Controllers works as well.
But now my collaps: I seperated my DataAccess from the Handlers, and obviously I'd like to inject them as well:
public class UserEndPointConfigurationHandler
{
private readonly DataAccess.UserEndPointAccess _access;
public UserEndPointConfigurationHandler(DataAccess.UserEndPointAccess access)
{
_access = access;
}
But bam, UserEndPointAccess can't be resolved. So it seems like even I directly request to DI an Class with a Parameterless-Constructor, I need to register that. For this case, sure I should Interface and register them, but what does that mean for internal helper classes I also inject?
According to the Docs: http://docs.asp.net/en/latest/fundamentals/dependency-injection.html#recommendations and also the examples I found, all people in the world only seem to communicate between Controllers and some Repositories. No Business-Layer and no Classes on different Abstraction-Levels in Assemblies.
Is the Microsoft DI approach something totally differnt than the good ol' Unity one, where I can really decouple as fine granular as I'd like to?
Thanks in advance.
Matthias
Edit #Nightowl: I add my answer here, since it's a bit longer.
First of all, Unity does automatically create Instances, if I request a conecrete Type. This allows me to inject Types I register and Types, like Helper classes etc. I don't need to. This combination allows me to use DI everywhere.
Also in your Example I'd need to know the DataAcces in the WebGui, which is quite thight coupled. Well, I know there are solutions for this via Reflection, but I hoped Microsoft did something in this Topic, but probably that'd mean to big of a change.
Also allows Unity to store Instances or Instructions how to create them, another huge feature, which is missing at the moment.
Probably I'm just to spoiled, what refined DI-Libraries do, probably they also do to much, but at the moment the Microsoft-Implementation is just a huge downgrade according to my Information.
MVC Core follows the the composition root pattern, which is where object graphs are created based off of a set of instructions to instantiate them. I think you are misinterpreting what the IServiceCollection is for. It does not store instances, it stores instructions on how to create instances. The instances aren't actually created until a constructor somewhere in the object graph requests one as a constructor parameter.
So, in short the reason why your service (which you call UserEndPointAccess) is not being instantiated when you request it is because you have not configured the IServiceCollection with instructions on how to create it.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.Configure<Model.Meta.AppSettings>(Configuration.GetSection("AppSettings"));
services.AddSingleton(typeof(Logic.UserEndPointConfigurationHandler));
services.AddSingleton(typeof(Logic.NetworkHandler));
// Need a way to instantiate UserEndPointAccess via DI.
services.AddSingleton(typeof(DataAccess.UserEndPointAccess));
services.AddMvc();
}
So it seems like even I directly request to DI an Class with a Parameterless-Constructor, I need to register that.
If you are doing DI correctly, each service class will only have a single constructor. If you have more than one it is known as the bastard injection anti-pattern, which essentially means you are tightly coupling your class definition to other classes by adding references to them as foreign defaults.
And yes, you need to register every type you require (that is not part of MVC's default registration). It is like that in Unity as well.

Where can Symfony services be useful?

There is the example of creating and using a service in the official documentation. At start we create some class, then register it in config/services.yml an then we can use it in our code like this:
$result = $this->get('app.myservice')->myMethod($arg);
//(In the [example][1] it is little bit other code:)
//$slug = $this->get('app.slugger')->slugify($post->getTitle());
But WHAT FOR? while I can just do the SAME like this:
use MyServiceNamespace/MyService
//...
$result = (new MyService())->myMethod($arg);
Where is profit of using Services? Is this just syntax sugar?
Nope. Far from syntax sugar.
You need to have a working understanding of what dependency injection means. Perhaps start by skimming through here: http://symfony.com/doc/current/book/service_container.html
Let's suppose your service needs a doctrine repository to do it's job. Which is better?
class MyController
{...
$userManager = $this->get('user.manager');
OR
$userRepository = $this->getDoctrine()->getManager()->getRepository('MyBundle::User');
$userManager = new UserManager($userRepository);
Your choice but once you have worked through the mechanics of how to add a service then you will never look back.
I should also point out that your sluglfy example requires a use statement and ties you code directly to a specific implementation. If you ever need to adjust your slugification then you need to go back and change all the places where it is used.
// These lines make your code more difficult to maintain
use Something\Slugify;
$slugify = new Slugify();
AS Opposed to
$slugify = $this->get('slugify');
'tIn this case, it's not really relevant. But from a simple design concern, services allow to make a better dependency management.
For instance, if you declare a service relaying on another one, then you won't have to instanciate both of them. Symfony will take care of it.
And since your declaration is centralized, any modification on the way you decide to create your service (= declare it), you won't have to change all the references to the services you changed since symfony will take care of the way it's instanciated when needed.
Another point is the scope of services. This information might be checked, but I think symfony instanciate service once (Singleton) which mean a better memory usage.

How does ninject work at a high level, how does it intercept object instantiation?

At a high level, how do these dep. injection frameworks work?
I can understand if you always instantiate an object via a custom factory like:
IUser user = DepInjector.Get<User>();
I'm guessing what happens is, wherever you defined the mappings, it will look at the type you want and try and find a match, if found, it will via reflection instantiate the type.
Are there dep. inj. frameworks that would work like:
IUser user = new User();
If so, how would it get the correct user, where is it hooking into the CLR to do this? In case of an asp.net website, is it any different?
If you want to know how Ninject works then the obvious place to start would be reading How Injection Works on their official wiki. It does use reflection but it now also uses dynamic methods:
"By default, the StandardKernel will
create dynamic methods (via
System.Reflection.Emit.DynamicMethod)
that can be used to inject values into
the different injection targets. These
dynamic methods are then triggered via
delegate calls."
As for you second example, I don't believe there are any DI frameworks that would do what you ask. However, constructor injection tends to be most common way of implementing IoC, so that when a class is constructed it knows what type to bind to via some configuration binding. So in your example IUser would be mapped to concrete User in config bindings so that any consuming class that has an IUser parameter as part of its constructor would get the correct User type passed in.
AFAIK there's no way to "hook into" object instantiation with the CLR. The only way to use DI in the second case would be to employ an assembly rewriter (i.e. a postprocessor similar to PostSharp) to replace the call to new with a call to the DI factory method (i.e. GetUser) in the compiled code.

Purpose of Unity Application Block in Microsoft Enterprise Library?

Can someone explain to me what is the purpose of the Unity Application Block? I tried looking through the documentation but its all very abstract.
What are some practical uses for the Unity block?
Inversion of Control
A quick summation (lot more reading is available this topic, and I highly suggest reading more)...
Microsoft's Unity from the Enterprise Patterns and Practices team is an Inversion of Control container project, or IoC for short. Just like Castle Windsor, StructureMap, etc. This type of development is also referred in lamen's terms as Loosely Coupling your components.
IoC includes a pattern for Dependency Injection of your objects, in which you rely on an external component to wire up the dependencies within your objects.
For example, instead of accessing static managers (which are near impossible to unit test), you create an object that relies on an external dependency to act upon. Let's take a Post service in which you want to access the DB to get a Post.
public class PostService : IPostService
{
private IPostRepository _postRepo;
public PostService(IPostRepository postRepo)
{
_postRepo = postRepo;
}
public IList<Post> GetPosts()
{
return _postRepo.GetAllPosts().ToList();
}
}
This PostService object now has an external dependency on IPostRepository. Notice how no concretes and no static manager classes are used? Instead, you have a loose-coupling of a simple Interface - which gives you the power of wiring up all different kinds of concrete classes that implement IPostRepository.
Microsoft Unity's purpose is to wire up that IPostRepository for you, automatically. So you never have to worry about doing:
// you never have to do this with Unity
IPostRepository repo = new PostRepository();
IPostService service = new PostService(repo); // dependency injection
IList<Post> posts = service.GetPosts();
The above shows where you have to implement two concrete classes, PostRepository() and PostService(). That is tightly-coupling your application to demand/require those exact instances, and leaves it very difficult to unit test.
Instead, you would use Unity in your end point (The controller in MVC, or code behind in ASPX pages):
IUnityContainer ioc = new UnityContainer();
IPostService postService = ioc.Resolve<IPostService>();
IList<Post> posts = postService.GetPosts();
Notice that there are no concretes used in this example (except UnityContainer and Post, obviously)! No concretes of the services, and no repository. That is loosely-coupling at its finest.
Here's the real kicker...
Unity (or any IoC container framework out there!) will inspect IPostService for any dependencies. It will see that it wants (depends) on an instance of IPostRepository. So, Unity will go into it's object map and look for the first object that implements IPostRepository that was registered with the container, and return it (i.e. a SqlPostRepository instance). That is the real power behind IoC frameworks - the power to inspect services and wire up any of the dependencies automatically.
I need to finish my blog post about the comparisons of UNity vs Castle vs StructureMap. I actually prefer Castle Windsor due to its configuration file options, and extensibility points personally.
The Unity Application Block is used for dependency injection. I think the best simple definition for DI is from this question
When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn't want you to have. You might even be looking for something we don't even have or which has expired.
What you should be doing is stating a need, "I need something to drink with lunch," and then we will make sure you have something when you sit down to eat.
So for an example,
IUnityContainer container = new UnityContainer();
ILunch lunch = container.Resolve<ILunch>();
Console.WriteLine(lunch.Drink);
This Outputs "Lemonade" because we defined Drink as a Dependency.
public class ILunch {
[Dependency]
public IDrink Drink { get; set; }
}
As far as practicality goes, Dependency Injection is really great when you have Dependencies on other objects and you don't want the developer to have to manually set them. It is that simple. It is also great for mocking. The most used example I can think of that I use is mocking a data layer. Sometimes the database isn't ready so instead of stopping development I have a fake layer that returns fake data. The data object is accessed via DI and can be configured to return objects which access the fake layer or the real layer. In this example I am almost using the DI Container as a configurable factory class. For more on Unity MSDN has some great resources http://msdn.microsoft.com/en-us/library/cc468366.aspx.
Other good DI Frameworks include Spring.NET and Ninject

Resources