Autofac: organising component registration logically - autofac

In an asp.net MVC application, rather than bloating Application_Start() with lots of Autofac scaffolding such as Component registrations, I wish to organise the application by having this is separate files.
Is there an example of a pattern I could follow for this? Is this what an autofac module is for?
For example, if i wanted all of the Widget-related registration in the same file, maybe in the Widget MVC area somewhere:
builder.RegisterType<FooWidget>().As<IWidget>();
builder.RegisterType<BarWidget>().As<IWidget>();

Yes. That is exactly what modules do. Depending on how much you need to register, you could choose to create a module per assembly, module per concept/type (i.e. ControllersModule, RepositoriesModule etc). In your case you might want to have a WidgetsModule. Your Application_Start() will then be nothing more than:
Assembly[] assemblies = BuildManager.GetReferencedAssemblies().OfType<Assembly>().ToArray();
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterAssemblyModules(assemblies);
IContainer container = containerBuilder.Build();
There are a lot of useful methods for registering types. It might minimize the amount of registration code to a point where it is fine to have it in a single place. In your example a RegisterAssemblyTypes(assembly).As<IWidget>() should be enough to register all IWidgets.
If I know I'm going to require a lot of registrations, I start with modules. Other times I start small and put all registrations in one place until the need arises for more readable/maintainable solution and then refactor towards modules.

Related

Unity container injection in my view models

I am a newcomer to C# / .Net / Prism / WPF / DevExpress and started to work on a big project in my company. As I am starting a bit late in the project, a lot of code was already produced and I stumble upon code like this very often:
public class AboutWindowViewModel : BindableBase
{
public AboutWindowViewModel(IUnityContainer container)
{
...
What I find "special" here is the dependence of the view model in the container. In the codebase I am currently looking at, it seems to be the "pattern". Every class gets a dependence in the IUnityContainer and then the dependencies are resolved manually with e.g.
container.ResolveEx<...>(...);
I am used to work with DI frameworks in other languages, so that example was just a non-sense to me because it goes against the definition of a DI framework and the problems it is meant to solve. For example, I tried to make up some code to test one of those view models and it turned out to be a nightmare.
Now, I addressed that concern to the developpers of my company and they answered me the following:
Prism recommendation is to resolve services using containers as they are needed.
Therefore, they resolve them all the time with the IUnityContainer.ResolveEx method.
My question is: is that really the recommended way to build up software with Prism??? If not, do you know where I can find documentation that clearly addresses that point with examples?
is that really the recommended way to build up software with Prism???
Not at all, in it's an anti-pattern.
Prism recommendation is to resolve services using containers as they are needed.
Not really just Prism, but more generally, the recommendation is to let the container resolve the dependencies. Of course, this can be done by calling Resolve manually, but in doing that one defeats all the benefits expected from dependency injection.
Rather, you want to list the dependencies as constructor parameters and let the container fill them. Your code does not need to depend on the container, except for the very entry-point ("resolution root"). The application should only ever contain a single Resolve statement that resolves the first instance.
Here's where Prism comes into play: in your PrismApplication.RegisterTypes and IModule.RegisterTypes, you configure your container. You tell it which type should implement which interface. Later on, when view models are needed, Prism (the ViewModelLocator to be precise) uses the container to resolve the view models, thereby resolving all the dependencies. There's no reason to make any class depend on the container, in fact, Prism doesn't register anything for IContainerRegistry in the first place.
Keep in mind that the container can not only inject singleton services, but also transient instances or factories. And if you need parametrized factories, you can always manually create and register complex factories.
On a side-note, I, personally, would be hesitant to work for a client with a code-base like this, as it's an obvious proof that their developers have no idea what they're doing.

Dagger2 - should an activity component be a sub-component of other?

I used #subcomponent mostly for case activities need to use some shared objects from application component, or fragments components want to use some objects provided by container activity.
Now I am wondering if I can make some activity components be subcomponent of another activity component. For example, the TaskDetailActivity has a task object and want to provide to some other activities such as TaskParticipantActivity, TaskProgressActivity and some fragments.
The traditional way to provide task object to other activities is set it into intent object, but how about if we want to use Dagger2 for this case?
Update: my sistuation similar with the case of UserScope in this article http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/, but instead of saving the user component in Application class, can I save in an activity, i.e TaskDetailActivity?
Components are for grouping objects of a similar lifecycle. While Components may happen to correspond to a particular set of functionality (like a TaskComponent for injecting a TaskActivity and a TaskPresenter) it is not always possible or desirable to insist on only one Component per set of functionality (for instance, insisting on only one TaskComponent for all task related activities and dependencies).
Instead, in Dagger 2 re-usability is available through Modules which you can very easily swap in and out of Components. Within the constraints of the advice for organising your Modules for testability in the Dagger 2 official documentation you are able to organise Modules congruent with your functionality (e.g., a TaskModule for all-task related dependencies). Then, because Components are so lightweight, you can make as many as you like to deal with the different lifecycles of your Activities and so on. Remember also that you can compose Modules using the Class<?> [] includes() method inside the Module #interface.
In your particular scenario, you want to share the Task object from a TaskDetailActivity. If you held a reference to the Task within your TaskDetailActivity then that reference will no longer be available when TaskDetailActivity is destroyed. While you could try some solution of holding binding the Task in a Module and then maintaining a reference to that Module at the app-scope level, you would essentially be doing the same as the UserScope at the app-scoped level in the article you have linked. Any kind of solution for sharing the Task object between Activity using Dagger 2 would necessarily involve maintaining a reference to the object at the app-scoped level.
Using Dagger 2 doesn't mean that the new keyword or serialization/deserialization of Parcelables is now wrong and so if your first intuition is to use Intent to communicate then I would say that you are right. If you need a more robust solution than directly communicating the Task, then you could extract a TaskRepository and transmit an Intent between Activity that contains the id of the Task you wish to retrieve. Indeed, some of the Google Android Architecture Blueprints have a solution just like this.

How to use modules in dagger-2

I can't seem to grasp the modules of dagger.
Should I create a new instance of a module each time I want to inject stuff?
Should I create only one instance of a module? If so where should I do it?
Is there a more complex example of fragments and activities used with dagger?
Thanks
You should think more about #Component than #Module. Modules just create objects that need further initialization. The actual work happens in Components, which modules are part of.
Should I create a new instance of a module each time I want to inject stuff?
You should create your module when you create the Component it is part of, since only this component is going to need it. If you find yourself creating the same module multiple times, you are most likely doing something wrong.
A module uses additional arguments (pass them in via the constructor) to create more complex objects. So if you were to have e.g. a UserModule you'd pass in the a user to create user dependent objects from the resulting component. If the user changes lose the old component and create a new module and a new component—the old objects should not be used anymore.
Keep the component where / when appropriate and be sure to use Scopes, since they determine the lifetime of your component.
Should I create only one instance of a module? If so where should I do it?
You most likely will just create a single instance of #Singleton annotated Components and Modules. In android you'd most likely keep the reference to the component (not the module!) in the Application or some real 'singleton'.
Is there a more complex example of fragments and activities used with dagger?
Try googling. There are lots of high quality tutorials with linked github repositories that go into much more depth and detail as would be possible here on SO. e.g. see Tasting dagger 2 on android.

manipulating other modules functionality in zend framework 2

How can I manipulate other modules without editing them ? very the same thing that wordpress modules do .
They add functionality to core system without changing the core code and they work together like a charm.
I always wanted to know how to implement this in my own modular application
A long time ago I wrote the blog post "Use 3rd party modules in Zend Framework 2" specifically about extending Zend Framework 2 modules. The answer from Bez is technically correct, it could be a bit more specific about the framework.
Read the full post at https://juriansluiman.nl/article/117/use-3rd-party-modules-in-zend-framework-2, but it gives you a clue about:
Changing a route from a module (say, you want to have the url /account/login instead of /user/login)
Overriding a view script, so you can completely modify the page's rendering
Changing a form object, so you could add new form fields or mark some required field as not required anymore.
This is a long topic, but here is a short gist.
Extensibility in Zend Framework 2 heavily relies on the premise that components can be interchanged, added, and/or substituted.
Read up on SOLID principles: http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)
Modules typically consists of objects working together as a well-oiled machinery, designed to accomplish one thing or a bunch of related things, whatever that may be. These objects are called services, and managed by the service locator/service manager.
A big part of making your module truly extensible is to expect your developers to extend a class or implement a certain interface, which the developer register as services. You should provide a mode of definition wherein the developers can specify which things he wants to substitute, and/or add their own services to -- and this is where the application configuration comes in.
Given the application configuration, you should construct your machinery a.k.a. module services according to options the developer has specified i.e., use the developer defined Foo\Bar\UserService service as the YourModule\UserServiceInterface within your module, etc. (This is usually delegated to service factories, which has the opportunity to read the application configuration, and constructs the appropriate object given a particular set of configuration values.)
EDIT:
To add, a lot can be accomplished by leveraging Zend's Zend\EventManager component. This allows you to give developers the freedom to hook and listen to certain operations of your module and act accordingly (See: http://en.wikipedia.org/wiki/Observer_pattern)

How can I use the new GWT MVP framework?

I need a tutorial for the new GWT MVP framework which is presented here.
The description Google gives is a little bit short for me. What are the meanings of — and how do I use — the following?
Activities
Places
Eventbus
ClientFactory
PlaceHistoryMapper
ActivityMapper
Also, where are the models in this new framework?
Places
These are classes that encode information about where your program has navigated. You might make a Place that means, "I'm on the home screen," and another one that means "I'm editing the user with id 52384. I think a better name for these would be PlaceTags, because they are not actually a place themselves - they just indicate where your program is. The URL is hooked to Places in a PlaceHistoryMapper, in which you can say, "hey, #home should generate a HomeScreenPlace and #edituser:52384 should generate a EditUserPlace (maybe constructed with a field you set to 52384).
Activities
These start and stop your code. Each Activity has a start method that is called when appropriate. You determine what "when appropriate" means by making an ActivityMapper, which has a function called getActivity. getActivity accepts a Place, and you have to decide which Activity to return. If the Place is whatever you've coded to mean "I'm on the home screen," you might return a HomeScreenActivity, and if the Place means "I'm editing the client with id 523584," you might return a EditClientActivity. You can add methods or a constructor to an activity to pass in an id like 523584.
EventBus
This is an object the different parts of your program use to communicate. If you don't want to, you don't need to know very much about it - you can just plug it in where indicated in Google's documentation (that you linked to)
ClientFactory
This is a centralized object whose only responsibility is making other objects. You can also skip this concept if you want to simplify things - you'll just be missing out on the central organization of your objects. The advantage is that if you want to switch them out later for, say, a mobile version, or a mocked-up-for-testing version, you can do so all at once within a single place and the rest of your program doesn't have to change at all. You can also reuse the same objects easily when coordinating from a central place, so you don't have to re-create the whole main screen every time someone goes to #home.
Your Actual Program
All this stuff is just for navigation. Your models, views, and presenters are all set up in each Activitys start() method, which the framework calls when your app should navigate to a new place. In the start method you should start up your presenter (usually using a new instance) and start up your display (usually reusing an instance - the client factory is good for this). When you've created your display, you let the framework know by setting it as the widget for the AcceptsOneWidget that the framework passed into your start method.
This is incomplete, but a good supplement to the docs you mentioned: http://code.google.com/intl/de-DE/webtoolkit/doc/latest/DevGuideMvpActivitiesAndPlaces.html
I would also recommend you to carefully listen to the Google I/O presentations, they are a golden key to understand the GWT philosophy:
http://www.google.com/events/io/2010/
http://www.google.com/events/io/2009/
Specially these ones (try to keep a more holistic view of the MVP framework). They do not talk about the real GWT implementation but they give you basic knowledge of MVP. I still am an 8 months noob, so from noob to noob :)
Ray Ryan's overview of the MVP paradigm. Great resource (it was an enlightening for me).
http://www.google.com/events/io/2009/sessions/GoogleWebToolkitBestPractices.html
http://www.google.com/events/io/2010/sessions/architecting-production-gwt.html
Daniel Danilatos's testing for GWT. Here you will understand why all the fuzz for MVP!
http://www.google.com/events/io/2010/sessions/gwt-continuous-build-testing.html