🔧 依赖注入支持同步函数注入

This commit is contained in:
洛水居室 2022-07-31 01:28:10 +08:00
parent b70e50133b
commit ed5da75c00
No known key found for this signature in database
GPG Key ID: C9DE87DA724B88FC

View File

@ -6,28 +6,43 @@ from model.types import Func
from utils.app.manager import ServiceDict from utils.app.manager import ServiceDict
def get_injections(func: Func):
injections = {}
try:
signature = inspect.signature(func)
except ValueError as exception:
if "no signature found" in str(exception):
Log.warning("no signature found", exception)
elif "not supported by signature" in str(exception):
Log.warning("not supported by signature", exception)
else:
raise exception
else:
for parameter_name, parameter in signature.parameters.items():
annotation = parameter.annotation
class_name = annotation.__name__
param = ServiceDict.get(class_name)
if param is not None:
injections.setdefault(parameter_name, param)
return injections
def inject(func: Func) -> Func: def inject(func: Func) -> Func:
"""依赖注入""" """依赖注入"""
@wraps(func) @wraps(func)
async def decorator(*args, **kwargs): async def async_decorator(*args, **kwargs):
try: injections = get_injections(func)
signature = inspect.signature(func) kwargs.update(injections)
except ValueError as exception:
if "no signature found" in str(exception):
Log.warning("no signature found", exception)
elif "not supported by signature" in str(exception):
Log.warning("not supported by signature", exception)
else:
raise exception
else:
for parameter_name, parameter in signature.parameters.items():
annotation = parameter.annotation
class_name = annotation.__name__
param = ServiceDict.get(class_name)
if param is not None:
kwargs.setdefault(parameter_name, param)
return await func(*args, **kwargs) return await func(*args, **kwargs)
return decorator @wraps(func)
def sync_decorator(*args, **kwargs):
injections = get_injections(func)
kwargs.update(injections)
return func(*args, **kwargs)
if inspect.iscoroutinefunction(func):
return async_decorator
else:
return sync_decorator