动态代理未完成代码(可能没问题)
using Autofac;
using Autofac.Extras.DynamicProxy;
using Castle.DynamicProxy;
using Castle.DynamicProxy.Internal;
using Hoa.Application.Authorization;
using Hoa.ServiceController;
using Hoa.ServiceController.Attributes;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Hoa.Application
{
public class HoaApplicationModule : Autofac.Module
{
private static readonly Func<Assembly, IEnumerable<Type>> queryControllerTypesExp =
ass => ass.GetTypes().Where(type => IsControllerType(type));
private static bool IsControllerType(Type type)
{
if ((!type.IsInterface && !type.IsAbstract && !type.IsGenericType && type.IsPublic)
&& ((type.IsDefined(typeof(HoaServiceControllerAttribute))
&& !type.IsDefined(typeof(HoaNonServiceWebApiAttribute))
&& (
!type.IsDefined(typeof(ApiExplorerSettingsAttribute))
|| (type.IsDefined(typeof(ApiExplorerSettingsAttribute)) && type.GetCustomAttribute<ApiExplorerSettingsAttribute>().IgnoreApi != true)
)
)
)) return true;
return false;
}
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<CatInterceptor>();
var controllerTypes = AppGlobal.ApplicationAssembiles.SelectMany(queryControllerTypesExp);
foreach (var type in controllerTypes)
{
var itype = type.GetAllInterfaces().FirstOrDefault();
builder.RegisterType(typeof(ServiceControllerProxy<>).MakeGenericType(itype))
.InterceptedBy(typeof(CatInterceptor))
.EnableClassInterceptors(ProxyGenerationOptions.Default, additionalInterfaces: itype);
}
}
}
public class CatInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
invocation.ReturnValue = invocation.Method.Invoke(
AppGlobal.AutofacContainer.Resolve(invocation.Method.DeclaringType), invocation.Arguments);
}
}
}
using Autofac;
using Hoa.Application;
using Hoa.Application.Authorization;
using Hoa.Application.Authorization.Dtos;
using Hoa.Helpers;
using Hoa.ServiceController;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
namespace Hoa.Web.Host.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class HoaController : ControllerBase
{
[HttpGet]
[Route(nameof(Author))]
public string Author()
{
var types = AppGlobal.AutofacContainer.ComponentRegistry.Registrations
.Where(r => r.Activator.LimitType.FullName.Contains("Proxy"))
.Select(r => r.Activator.LimitType).ToArray();
var cat = AppGlobal.AutofacContainer.Resolve(typeof(ServiceControllerProxy<>).MakeGenericType(typeof(IAuthorizationAppService)));
var result = cat.GetType().GetMethod("SignIn").Invoke(cat, new object[]{
new SignInInput()
{
}});
return "Powered by Monk";
}
}
}
如果您觉得本文对你有用,不妨帮忙点个赞,或者在评论里给我一句赞美,小小成就都是今后继续为大家编写优质文章的动力,百小僧拜谢!
欢迎您持续关注我的博客:)
版权所有,欢迎保留原文链接进行转载:)