Skip to content

Commit

Permalink
HttpServer支持Controller的构造函数注入
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Feb 29, 2024
1 parent c1b460a commit 053b57c
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 8 deletions.
11 changes: 7 additions & 4 deletions NewLife.Core/Http/ControllerHandler.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Collections;
using System.Reflection;
using NewLife.Model;
using NewLife.Reflection;
using NewLife.Remoting;

Expand All @@ -17,15 +18,17 @@ public class ControllerHandler : IHttpHandler
/// <param name="context"></param>
public virtual void ProcessRequest(IHttpContext context)
{
if (ControllerType == null) return;
var type = ControllerType;
if (type == null) return;

var ss = context.Path.Split('/');
var methodName = ss.Length >= 3 ? ss[2] : null;

var controller = ControllerType.CreateInstance();
// 优先使用服务提供者创建控制器对象,以便控制器构造函数注入
var controller = context.ServiceProvider?.CreateInstance(type) ?? type.CreateInstance();

var method = methodName == null ? null : ControllerType.GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (method == null) throw new ApiException(ApiCode.NotFound, $"Cannot find operation [{methodName}] within controller [{ControllerType.FullName}]");
var method = methodName == null ? null : type.GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (method == null) throw new ApiException(ApiCode.NotFound, $"Cannot find operation [{methodName}] within controller [{type.FullName}]");

var result = controller.InvokeWithParams(method, context.Parameters as IDictionary);
if (result != null)
Expand Down
5 changes: 4 additions & 1 deletion NewLife.Core/Http/HttpSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,10 @@ protected virtual HttpResponse ProcessRequest(HttpRequest request, ReceivedEvent
var handler = server?.MatchHandler(path);
if (handler == null) return new HttpResponse { StatusCode = HttpStatusCode.NotFound };

var context = new DefaultHttpContext(this, request, path, handler);
var context = new DefaultHttpContext(this, request, path, handler)
{
ServiceProvider = this
};

try
{
Expand Down
6 changes: 6 additions & 0 deletions NewLife.Core/Http/IHttpContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ public interface IHttpContext
/// <summary>处理器</summary>
IHttpHandler? Handler { get; }

/// <summary>服务提供者</summary>
IServiceProvider? ServiceProvider { get; }

/// <summary>请求参数</summary>
IDictionary<String, Object?> Parameters { get; }
#endregion
Expand Down Expand Up @@ -52,6 +55,9 @@ public class DefaultHttpContext : IHttpContext
/// <summary>处理器</summary>
public IHttpHandler? Handler { get; set; }

/// <summary>服务提供者</summary>
public IServiceProvider? ServiceProvider { get; set; }

/// <summary>请求参数</summary>
public IDictionary<String, Object?> Parameters { get; } = new NullableDictionary<String, Object?>(StringComparer.OrdinalIgnoreCase);
#endregion
Expand Down
17 changes: 16 additions & 1 deletion NewLife.Core/Net/NetSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public class NetSession<TServer> : NetSession where TServer : NetServer
///
/// 实际应用可通过重载OnReceive实现收到数据时的业务逻辑。
/// </remarks>
public class NetSession : DisposeBase, INetSession, IExtend
public class NetSession : DisposeBase, INetSession, IServiceProvider, IExtend
{
#region 属性
/// <summary>唯一会话标识。在主服务中唯一标识当前会话,原子自增</summary>
Expand Down Expand Up @@ -307,5 +307,20 @@ public virtual String LogPrefix
/// <summary>已重载。</summary>
/// <returns></returns>
public override String ToString() => $"{(this as INetSession).Host?.Name}[{ID}] {Session}";

/// <summary>获取服务</summary>
/// <param name="serviceType"></param>
/// <returns></returns>
public virtual Object GetService(Type serviceType)
{
if (serviceType == typeof(IServiceProvider)) return this;
if (serviceType == typeof(NetSession)) return this;
if (serviceType == typeof(INetSession)) return this;
if (serviceType == typeof(NetServer)) return (this as INetSession).Host;
if (serviceType == typeof(ISocketSession)) return Session;
if (serviceType == typeof(ISocketServer)) return Server;

return ServiceProvider!.GetService(serviceType)!;
}
#endregion
}
19 changes: 17 additions & 2 deletions Test/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
using NewLife.Http;
using NewLife.IO;
using NewLife.Log;
using NewLife.Model;
using NewLife.Net;
using NewLife.Remoting;
using NewLife.Security;
Expand Down Expand Up @@ -73,7 +74,7 @@ private static async Task Main(String[] args)
try
{
#endif
Test6();
Test5();
#if !DEBUG
}
catch (Exception ex)
Expand Down Expand Up @@ -280,19 +281,24 @@ private static void Test4()
private static NetServer _server;
private static async void Test5()
{
var provider = ObjectContainer.Provider;

var server = new HttpServer
{
Port = 8080,
ServiceProvider = provider,

Log = XTrace.Log,
//SessionLog = XTrace.Log,
};
server.Map("/", () => "<h1>Hello NewLife!</h1></br> " + DateTime.Now.ToFullString() + "</br><img src=\"logos/leaf.png\" />");
server.Map("/user", (String act, Int32 uid) => new { code = 0, data = $"User.{act}({uid}) success!" });
server.MapStaticFiles("/logos", "images/");
server.MapStaticFiles("/", "./");
//server.MapController<ApiController>("/api");
server.MapController<MyHttpController>("/api");
server.Map("/my", new MyHttpHandler());
server.Map("/ws", new WebSocketHandler());
server.MapStaticFiles("/", "./");
server.Start();

_server = server;
Expand Down Expand Up @@ -330,6 +336,15 @@ public void ProcessRequest(IHttpContext context)
}
}

private class MyHttpController
{
private readonly NetSession _session;

public MyHttpController(NetSession session) => _session = session;

public String Info() => $"你好 {_session.Remote},现在时间是:{DateTime.Now.ToFullString()}";
}

private static void Test6()
{
XTrace.WriteLine("TLS加密通信");
Expand Down

0 comments on commit 053b57c

Please sign in to comment.