Use Autofac for dependency injection in specficic namespace

I want to add DispatcherNotifiedObservableCollection to (and only to) all ViewModels (located in MyProject.ViewModels) as an ObservableCollection.

With Ninject, I can accomplish this with

Bind(typeof(ObservableCollection<>))
    .To(typeof(DispatcherNotifiedObservableCollection<>))
    .When(context => context.ParentContext.Binding
        .Service.Namespace == "MyProject.ViewModels");

I learned from Nicholas Bloomhardt: Autofac vs Ninject context binding?

that Autofac does not provide this functionality, but some workaround may be applied.

Thank!

(sorry for my English)

Edit 1: Name changed for better description.

Edit 2, 3: Changed content and title for a better description.

+3
source share
1 answer

Sorry for the slow reply.

Autofac, ViewModel ObservableCollection<>:

// Default for other components
builder.RegisterGeneric(typeof(ObservableCollection<>));

// Won't be picked up by default
builder.RegisterGeneric(typeof(DispatcherNotifiedObservableCollection<>))
    .Named("dispatched", typeof(ObservableCollection<>));

var viewModelAssembly = typeof(AViewModel).Assembly;
builder.RegisterAssemblyTypes(viewModelAssembly)
    .Where(t => t.Name != null && t.Name.EndsWith("ViewModel"))
    .WithParameter(
        (pi, c) => pi.ParameterType.IsClosedTypeOf(typeof(ObservableCollection<>)),
        (pi, c) => c.ResolveNamed("dispatched", pi.ParameterType));

using Autofac; IsClosedTypeOf(). , Autofac, , WithParameter(), , Parameter ResolvedParameter.

, ,

+8

Source: https://habr.com/ru/post/1788872/


All Articles