2
votes

Autofac's default is to use the constructor with the most parameters yet it keeps hitting the parameterless default constructor.

Consuming class:

using AlbumApp.Core.Common.Contracts;
using AlbumApp.Core.Common.UI.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AlbumApp.Admin.ViewModels
{
  public class MainViewModel : ViewModelBase
  {
    private static IServiceFactory _serviceFactory;

    public MainViewModel() { }

    public MainViewModel(IServiceFactory serviceFactory)
    { _serviceFactory = serviceFactory; }

    private DashboardViewModel _dashboardViewModel = new DashboardViewModel(_serviceFactory);

    public DashboardViewModel DashboardViewModel { get { return _dashboardViewModel; } private set { } } // = new DashboardViewModel();
  }
}

AutofacLoader:

using AlbumApp.Client.Proxies;
using AlbumApp.Core.Common.Contracts;
using Autofac;
using System.Reflection;

namespace AlbumApp.Admin.Bootstrapper
{
  public static class AutoFacLoader
  {
    public static IContainer Init() { 
      var builder = Builder();
      return builder.Build(); }

    public static ContainerBuilder Builder() {
      var builder = new ContainerBuilder();
      builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
        .InNamespace("AlbumApp.Admin.ViewModels").SingleInstance();
      builder.RegisterType<ServiceFactory>().As<IServiceFactory>();

      return builder; }
  }
}

App.xaml.cs

using AlbumApp.Admin.Bootstrapper;
using AlbumApp.Core.Common.Core;
using System.Windows;

namespace AlbumApp.Admin
{
  /// <summary>
  /// Interaction logic for App.xaml
  /// </summary>
  public partial class App : Application
  {
    protected override void OnStartup(StartupEventArgs e)
    {
      base.OnStartup(e);

      ObjectBase.Container = AutoFacLoader.Init();

    }
  }
}

When I set a breakpoint on the builder.Build and check the ComponentRegistry it contains the ServiceFactory.

{Activator = ServiceFactory (ReflectionActivator), Services = [AlbumApp.Core.Common.Contracts.IServiceFactory], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope}

I also set a breakpoint on the two constructors of the MainViewModel and only the default constructor is hit so the _serviceFactory is null.

How do I get Autofac to inject a ServiceFactory?

Call Stack on parameterless constructor:

AlbumApp.Admin.exe!AlbumApp.Admin.ViewModels.MainViewModel.MainViewModel() Line 15 C# AlbumApp.Admin.exe!AlbumApp.Admin.MainWindow.MainWindow() Line 30 C# [Native to Managed Transition]
[Managed to Native Transition]
mscorlib.dll!System.RuntimeType.CreateInstanceSlow(bool publicOnly, bool skipCheckThis, bool fillCache, ref System.Threading.StackCrawlMark stackMark) Unknown mscorlib.dll!System.Activator.CreateInstance(System.Type type, bool nonPublic) Unknown mscorlib.dll!System.RuntimeType.CreateInstanceImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes, ref System.Threading.StackCrawlMark stackMark) Unknown mscorlib.dll!System.Activator.CreateInstance(System.Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes) Unknown mscorlib.dll!System.Activator.CreateInstance(System.Type type, object[] args) Unknown System.Xaml.dll!System.Xaml.Schema.SafeReflectionInvoker.CreateInstanceCritical(System.Type type, object[] arguments) Unknown System.Xaml.dll!System.Xaml.Schema.SafeReflectionInvoker.CreateInstance(System.Type type, object[] arguments) Unknown System.Xaml.dll!System.Xaml.Schema.XamlTypeInvoker.CreateInstanceWithActivator(System.Type type, object[] arguments) Unknown System.Xaml.dll!System.Xaml.Schema.XamlTypeInvoker.CreateInstance(object[] arguments) Unknown System.Xaml.dll!MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstanceWithCtor(System.Xaml.XamlType xamlType, object[] args) Unknown System.Xaml.dll!MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstance(System.Xaml.XamlType xamlType, object[] args) Unknown System.Xaml.dll!MS.Internal.Xaml.Runtime.PartialTrustTolerantRuntime.CreateInstance(System.Xaml.XamlType xamlType, object[] args) Unknown System.Xaml.dll!System.Xaml.XamlObjectWriter.Logic_CreateAndAssignToParentStart(MS.Internal.Xaml.Context.ObjectWriterContext ctx) Unknown System.Xaml.dll!System.Xaml.XamlObjectWriter.WriteStartMember(System.Xaml.XamlMember property) Unknown System.Xaml.dll!System.Xaml.XamlWriter.WriteNode(System.Xaml.XamlReader reader) Unknown PresentationFramework.dll!System.Windows.Markup.WpfXamlLoader.TransformNodes(System.Xaml.XamlReader xamlReader, System.Xaml.XamlObjectWriter xamlWriter, bool onlyLoadOneNode, bool skipJournaledProperties, bool shouldPassLineNumberInfo, System.Xaml.IXamlLineInfo xamlLineInfo, System.Xaml.IXamlLineInfoConsumer xamlLineInfoConsumer, MS.Internal.Xaml.Context.XamlContextStack stack, System.Windows.Markup.IStyleConnector styleConnector) Unknown PresentationFramework.dll!System.Windows.Markup.WpfXamlLoader.Load(System.Xaml.XamlReader xamlReader, System.Xaml.IXamlObjectWriterFactory writerFactory, bool skipJournaledProperties, object rootObject, System.Xaml.XamlObjectWriterSettings settings, System.Uri baseUri) Unknown PresentationFramework.dll!System.Windows.Markup.WpfXamlLoader.LoadBaml(System.Xaml.XamlReader xamlReader, bool skipJournaledProperties, object rootObject, System.Xaml.Permissions.XamlAccessLevel accessLevel, System.Uri baseUri) Unknown PresentationFramework.dll!System.Windows.Markup.XamlReader.LoadBaml(System.IO.Stream stream, System.Windows.Markup.ParserContext parserContext, object parent, bool closeStream) Unknown PresentationFramework.dll!System.Windows.Application.LoadBamlStreamWithSyncInfo(System.IO.Stream stream, System.Windows.Markup.ParserContext pc) Unknown PresentationFramework.dll!System.Windows.Application.LoadComponent(System.Uri resourceLocator, bool bSkipJournaledProperties) Unknown PresentationFramework.dll!System.Windows.Application.DoStartup() Unknown PresentationFramework.dll!System.Windows.Application..ctor.AnonymousMethod__1_0(object unused) Unknown WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs) Unknown WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source, System.Delegate callback, object args, int numArgs, System.Delegate catchHandler) Unknown WindowsBase.dll!System.Windows.Threading.Dispatcher.WrappedInvoke(System.Delegate callback, object args, int numArgs, System.Delegate catchHandler) Unknown WindowsBase.dll!System.Windows.Threading.DispatcherOperation.InvokeImpl() Unknown WindowsBase.dll!System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(object state) Unknown mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Unknown WindowsBase.dll!MS.Internal.CulturePreservingExecutionContext.Run(MS.Internal.CulturePreservingExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Unknown WindowsBase.dll!System.Windows.Threading.DispatcherOperation.Invoke() Unknown WindowsBase.dll!System.Windows.Threading.Dispatcher.ProcessQueue() Unknown WindowsBase.dll!System.Windows.Threading.Dispatcher.WndProcHook(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) Unknown WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) Unknown WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o) Unknown WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs) Unknown WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source, System.Delegate callback, object args, int numArgs, System.Delegate catchHandler) Unknown WindowsBase.dll!System.Windows.Threading.Dispatcher.WrappedInvoke(System.Delegate callback, object args, int numArgs, System.Delegate catchHandler) Unknown WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs) Unknown WindowsBase.dll!System.Windows.Threading.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority priority, System.Delegate method, object arg) Unknown WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam) Unknown [Native to Managed Transition]
[Managed to Native Transition]
WindowsBase.dll!System.Windows.Threading.Dispatcher.TranslateAndDispatchMessage(ref System.Windows.Interop.MSG msg) Unknown WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame) Unknown WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) Unknown WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() Unknown PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) Unknown PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) Unknown PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) Unknown PresentationFramework.dll!System.Windows.Application.Run() Unknown AlbumApp.Admin.exe!AlbumApp.Admin.App.Main() Unknown [Native to Managed Transition]
[Managed to Native Transition]
mscorlib.dll!System.AppDomain.nExecuteAssembly(System.Reflection.RuntimeAssembly assembly, string[] args) Unknown mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) Unknown Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() Unknown mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) Unknown mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Unknown mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() Unknown

1
Could you add a breakpoint on the constructor and post the stack trace ? The type may not be initialized by Autofac.Cyril Durand
What stack trace? There is no error thrown so there is no stack trace. It never hits the constructor with the IServiceFactory serviceFactory parameter.Joe
I meant call stack when the parameterless constructor is hitted.Cyril Durand
It' been posted.Joe
Your class is not constructed by Autofac but by WPF. How do you link your AutoFacLoader to your WPF application ? I don't know enough about WPF but the problem seems to be there.Cyril Durand

1 Answers

1
votes

The ViewModelBase class contains the AutoFac Container which gets populated in the App.xaml.cs. Initialize the ViewModels by resolving them from the Container.

Updated MainViewModel.cs

  public class MainViewModel : ViewModelBase
  {
    public MainViewModel() { } 

    public DashboardViewModel DashboardViewModel {
      get { return Container.Resolve<DashboardViewModel>(); }    private set { } }

    public MaintainAlbumsViewModel MaintainAlbumsViewModel {
      get { return Container.Resolve<MaintainAlbumsViewModel>(); }     private set { } }

    public OrdersViewModel OrdersViewModel {
      get { return Container.Resolve<OrdersViewModel>(); }       private set { }
    }
  }