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)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类型,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)未知 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)未知 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,布尔onlyLoadOneNode,布尔skipJournaledProperties,布尔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()未知 PresentationFramework.dll!System.Windows.Application..ctor.AnonymousMethod__1_0(对象未使用)未知 WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback,object args,int numArgs)Unknown WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(对象源,System.Delegate回调,对象args,int numArgs,System.Delegate catchHandler)未知 WindowsBase.dll!System.Windows.Threading.Dispatcher.WrappedInvoke(System.Delegate回调,对象args,int numArgs,System.Delegate catchHandler)未知 WindowsBase.dll!System.Windows.Threading.DispatcherOperation.InvokeImpl()未知 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()未知 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 handling)Unknown WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd,int msg,System.IntPtr wParam,System.IntPtr lParam,ref bool handling)Unknown WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o)未知 WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback,object args,int numArgs)Unknown WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(对象源,System.Delegate回调,对象args,int numArgs,System.Delegate catchHandler)未知 WindowsBase.dll!System.Windows.Threading.Dispatcher.WrappedInvoke(System.Delegate回调,对象args,int numArgs,System.Delegate catchHandler)未知 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)未知 [原产于管理过渡]
[管理到原生过渡]
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()未知 PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore)未知 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()未知 AlbumApp.Admin.exe!AlbumApp.Admin.App.Main()未知 [原产于管理过渡]
[管理到原生过渡]
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()未知 mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state)未知 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()未知
答案 0 :(得分:0)
produceOutput
类包含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 { }
}
}