问题
I am writing unit tests for my IOC. One of my interfaces injects IServerEvents.
I am including events via:
ServerEventsFeature serverEventsFeature = new ServerEventsFeature()
{
LimitToAuthenticatedUsers = false,
NotifyChannelOfSubscriptions = false,
OnConnect = (eventSubscription, dictionary) =>
{
},
OnSubscribe = (eventSubscription) =>
{
}
};
However, container.Resolve gives the following error when debugging (Not through unit tests) :
'container.Resolve<IServerEvents>()' threw an exception of type 'System.Exception'
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: {System.InvalidOperationException: No service for type 'ServiceStack.IServerEvents' has been registered.
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Funq.Container.ResolveImpl[TService](String name, Boolean throwIfMissing)}
Message: "Error trying to resolve Service 'ServiceStack.IServerEvents' or one of its autowired dependencies (see inner exception for details)."
Source: "ServiceStack"
StackTrace: " at Funq.Container.ResolveImpl[TService](String name, Boolean throwIfMissing)"
TargetSite: {TService ResolveImpl[TService](System.String, Boolean)}
This does work in normal usage, but manual Resolve of the interface does not work.
What I am wondering is :
A) proper way to unit test this integration of server events
B) Should I merely mock the IServerEvents on the container with a RegisterAs<>() in unit tests
C) Why the injection works fine but container.Resolve() fails.
Any feedback is appreciated.
回答1:
You can't use ServerEventsFeature
in a unit test, you'll only be able to make use of it in an integration test. You can find some working examples in ServerEventTests.
As ServerEventsFeature
is a plugin, it needs to be registered as a plugin to function:
Plugins.Add(new ServerEventsFeature { ... });
Which when the plugin is registered will register the MemoryServerEvents dependency:
container.Register<IServerEvents>(memoryServerEvents);
来源:https://stackoverflow.com/questions/54406393/ioc-injection-of-iserversideevents