// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNetCore.Mvc.Internal; using Microsoft.AspNetCore.Mvc.ViewFeatures; namespace Microsoft.AspNetCore.Mvc.ViewComponents { /// /// A default implementation of . /// /// /// The can provide the current instance of /// to a public property of a view component marked /// with . /// public class DefaultViewComponentActivator : IViewComponentActivator { private readonly ITypeActivatorCache _typeActivatorCache; /// /// Initializes a new instance of class. /// /// /// The used to create new view component instances. /// #pragma warning disable PUB0001 // Pubternal type in public API public DefaultViewComponentActivator(ITypeActivatorCache typeActivatorCache) #pragma warning restore PUB0001 { if (typeActivatorCache == null) { throw new ArgumentNullException(nameof(typeActivatorCache)); } _typeActivatorCache = typeActivatorCache; } /// public virtual object Create(ViewComponentContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var componentType = context.ViewComponentDescriptor.TypeInfo; if (componentType == null) { throw new ArgumentException(Resources.FormatPropertyOfTypeCannotBeNull( nameof(context.ViewComponentDescriptor.TypeInfo), nameof(context.ViewComponentDescriptor))); } var viewComponent = _typeActivatorCache.CreateInstance( context.ViewContext.HttpContext.RequestServices, context.ViewComponentDescriptor.TypeInfo.AsType()); return viewComponent; } /// public virtual void Release(ViewComponentContext context, object viewComponent) { if (context == null) { throw new InvalidOperationException(nameof(context)); } if (viewComponent == null) { throw new InvalidOperationException(nameof(viewComponent)); } var disposable = viewComponent as IDisposable; if (disposable != null) { disposable.Dispose(); } } } }