Autofac не попадает в конструктор с параметром - PullRequest
0 голосов
/ 02 мая 2018

По умолчанию Autofac использует конструктор с большинством параметров, но при этом он продолжает использовать конструктор по умолчанию без параметров.

Класс потребления:

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();

    }
  }
}

Когда я устанавливаю breakpoint на builder.Build и проверяю ComponentRegistry, он содержит ServiceFactory.

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

Я также установил точку останова для двух конструкторов MainViewModel, и ударил только конструктор по умолчанию, поэтому _serviceFactory является нулевым.

Как мне заставить Autofac ввести ServiceFactory?

Стек вызовов для конструктора без параметров:

AlbumApp.Admin.exe! AlbumApp.Admin.ViewModels.MainViewModel.MainViewModel () Строка 15 C # AlbumApp.Admin.exe! AlbumApp.Admin.MainWindow.MainWindow () Строка 30 C # [Родной для управляемого перехода]
[Управляемый для нативного перехода]
mscorlib.dll! System.RuntimeType.CreateInstanceSlow (bool publicOnly, bool skipCheckThis, bool fillCache, ref System.Threading.StackCrawlMark stackMark) Неизвестно mscorlib.dll! System.Activator.CreateInstance (тип System.Type, bool nonPublic) Неизвестно mscorlib.dll! System.RuntimeType.CreateInstanceImpl (привязка System.Reflection.BindingFlags bindingAttr, привязка System.Reflection.Binder, аргументы объекта [], System.Globalization.CultureInfo культура, объект [] активацияAttributes, ссылка System.Threading.StackCrawlMark UnknownMack mscorlib.dll! System.Activator.CreateInstance (тип System.Type, привязка System.Reflection.BindingFlagsAttr, связыватель System.Reflection.Binder, аргументы object [], System.Globalization.CultureInfo culture, object [] активацииAttributes) Неизвестный mscorlib.dll! System.Activator.CreateInstance (тип System.Type, аргументы object []) Неизвестно System.Xaml.dll! System.Xaml.Schema.SafeReflectionInvoker.CreateInstanceCritical (тип System.Type, аргументы object []) Неизвестно System.Xaml.dll! System.Xaml.Schema.SafeReflectionInvoker.CreateInstance (тип System.Type, аргументы object []) Неизвестно System.Xaml.dll! System.Xaml.Schema.XamlTypeInvoker.CreateInstanceWithActivator (тип System.Type, аргументы object []) Неизвестно System.Xaml.dll! System.Xaml.Schema.XamlTypeInvoker.CreateInstance (аргументы объекта []) Неизвестно System.Xaml.dll! MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstanceWithCtor (System.Xaml.XamlType xamlType, object [] args) Неизвестно System.Xaml.dll! MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstance (System.Xaml.XamlType xamlType, object [] args) Неизвестно System.Xaml.dll! MS.Internal.Xaml.Runtime.PartialTrustTolerantRuntime.CreateInstance (System.Xaml.XamlType xamlType, object [] args) Неизвестно System.Xaml.dll! System.Xaml.XamlObjectWriter.Logic_CreateAndAssignToParentStart (MS.Internal.Xaml.Context.ObjectWriterContext ctx) Неизвестно System.Xaml.dll! System.Xaml.XamlObjectWriter.WriteStartMember (свойство System.Xaml.XamlMember) Неизвестно System.Xaml.dll! System.Xaml.XamlWriter.WriteNode (читатель System.Xaml.XamlReader) Неизвестно 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) Неизвестно PresentationFramework.dll! System.Windows.Markup.WpfXamlLoader.PresentationFramework.dll! System.Windows.Markup.WpfXamlLoader.LoadBaml (System.Xaml.XamlReader xamlReader, bool skipJournaledProperties, объект rootObject, System.Xaml.Permissions.XamlAccessLevel, доступный уровень, неизвестный базовый уровень System.Uri PresentationFramework.dll! System.Windows.Markup.XamlReader.LoadBaml (поток System.IO.Stream, System.Windows.Markup.ParserContext parserContext, родительский объект, bool closeStream) неизвестен PresentationFramework.dll! System.Windows.Application.LoadBamlStreamWithSyncInfo (поток System.IO.Stream, System.Windows.Markup.ParserContext pc) неизвестен PresentationFramework.dll! System.Windows.Application.LoadComponent (System.Uri resourceLocator, bool bSkipJournaledProperties) Неизвестный PresentationFramework.dll! System.Windows.Application.DoStartup () Неизвестно PresentationFramework.dll! System.Windows.Application..ctor.AnonymousMethod__1_0 (объект не используется) Неизвестно WindowsBase.dll! System.Windows.Threading.ExceptionWrapper.InternalRealCall (обратный вызов System.Delegate, аргументы объекта, int numArgs) Неизвестно WindowsBase.dll! System.Windows.Threading.ExceptionWrapper.TryCatchWhen (источник объекта, обратный вызов System.Delegate, аргументы объекта, int numArgs, System.Delegate catchHandler) Неизвестно WindowsBase.dll! System.Windows.Threading.Dispatcher.WrappedInvoke (обратный вызов System.Delegate, аргументы объекта, int numArgs, System.Delegate catchHandler) Неизвестно WindowsBase.dll! System.Windows.Threading.DispatcherOperation.InvokeImpl () Неизвестно WindowsBase.dll! System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext (состояние объекта) Неизвестно mscorlib.dll! System.Threading.ExecutionContext.RunInternal (System.Threading.ExecutionContext executeContext, System.Threading.ContextCallback обратный вызов, состояние объекта, bool preserveSyncCtx) Неизвестно mscorlib.dll! System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executeContext, System.Threading.ContextCallback обратный вызов, состояние объекта, bool preserveSyncCtx) Неизвестно mscorlib.dll! System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executeContext, System.Threading.ContextCallback обратный вызов, состояние объекта) Неизвестно WindowsBase.dll! MS.Internal.CulturePreservingExecutionContext.Run (MS.Internal.CulturePreservingExecutionContext executeContext, обратный вызов System.Threading.ContextCallback, состояние объекта) Неизвестно WindowsBase.dll! System.Windows.Threading.DispatcherOperation.Invoke () Неизвестно WindowsBase.dll! System.Windows.Threading.Dispatcher.ProcessQueue () Неизвестно WindowsBase.dll! System.Windows.Threading.Dispatcher.WndProcHook (System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool обрабатывается) Неизвестно WindowsBase.dll! MS.Win32.HwndWrapper.WndProc (System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool обрабатывается) Неизвестно WindowsBase.dll! MS.Win32.HwndSubclass.DispatcherCallbackOperation (объект o) Неизвестно WindowsBase.dll! System.Windows.Threading.ExceptionWrapper.InternalRealCall (обратный вызов System.Delegate, аргументы объекта, int numArgs) Неизвестно WindowsBase.dll! System.Windows.Threading.ExceptionWrapper.TryCatchWhen (источник объекта, обратный вызов System.Delegate, аргументы объекта, int numArgs, System.Delegate catchHandler) Неизвестно WindowsBase.dll! System.Windows.Threading.Dispatcher.WrappedInvoke (обратный вызов System.Delegate, аргументы объекта, int numArgs, System.Delegate catchHandler) Неизвестно WindowsBase.dll! System.Windows.Threading.Dispatcher.LegacyInvokeImpl (приоритет System.Windows.Threading.DispatcherPriority, время ожидания System.TimeSpan, метод System.Delegate, аргументы объекта, int numArgs) Неизвестно WindowsBase.dll! System.Windows.Threading.Dispatcher.Invoke (приоритет System.Windows.Threading.DispatcherPriority, метод System.Delegate, объектный аргумент) Неизвестно WindowsBase.dll! MS.Win32.HwndSubclass.SubclassWndProc (System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam) Неизвестно[Родной для управляемого перехода]
[Управляемый к нативному переходу]
WindowsBase.dll! System.Windows.Threading.Dispatcher.TranslateAndDispatchMessage (ref System.Windows.Interop.MSG msg) Неизвестно WindowsBase.dll! System.Windows.Threading.Dispatcher.PushFrameImpl (фрейм System.Windows.Threading.DispatcherFrame) Неизвестно WindowsBase.dll! System.Windows.Threading.Dispatcher.PushFrame (кадр System.Windows.Threading.DispatcherFrame) Неизвестно WindowsBase.dll! System.Windows.Threading.Dispatcher.Run () Неизвестно PresentationFramework.dll! System.Windows.Application.RunDispatcher (объект игнорируется) Неизвестно PresentationFramework.dll! System.Windows.Application.RunInternal (окно System.Windows.Window) Неизвестно PresentationFramework.dll! System.Windows.Application.Run (окно System.Windows.Window) Неизвестно PresentationFramework.dll! System.Windows.Application.Run () Неизвестно AlbumApp.Admin.exe! AlbumApp.Admin.App.Main () Неизвестно [Родной для управляемого перехода]
[Управляемый к нативному переходу]
mscorlib.dll! System.AppDomain.nExecuteAssembly (сборка System.Reflection.RuntimeAssembly, строка [] args) Неизвестно mscorlib.dll! System.AppDomain.ExecuteAssembly (строка assemblyFile, System.Security.Policy.Evidence assemblySecurity, string [] args) Неизвестно Microsoft.VisualStudio.HostingProcess.Utilities.dll! Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly () Неизвестно mscorlib.dll! System.Threading.ThreadHelper.ThreadStart_Context (состояние объекта) Неизвестно mscorlib.dll! System.Threading.ExecutionContext.RunInternal (System.Threading.ExecutionContext executeContext, System.Threading.ContextCallback обратный вызов, состояние объекта, bool preserveSyncCtx) Неизвестно mscorlib.dll! System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executeContext, System.Threading.ContextCallback обратный вызов, состояние объекта, bool preserveSyncCtx) Неизвестно mscorlib.dll! System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executeContext, System.Threading.ContextCallback обратный вызов, состояние объекта) Неизвестно mscorlib.dll! System.Threading.ThreadHelper.ThreadStart () Неизвестно

1 Ответ

0 голосов
/ 11 мая 2018

Класс ViewModelBase содержит AutoFac Container, который заполняется в App.xaml.cs. Инициализируйте ViewModels, разрешив их из Container.

Обновлен 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 { }
    }
  }
...