WCF with Ninject throwing ArgumentNullException - wcf

I am new to Ninject and trying to evaluate how well it compares to Windsor Castle, which I am more familiar with. My application is a WCF service application hosted in IIS. As a result, I am trying to spin-up the container/kernel and use the NinjectServiceHostFactory to create my service class, etc. Unfortunately, I'm getting an ArgumentNullException instead.
Here's the exception information:
System.ArgumentNullException
Cannot be null. Parameter name: root
at Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot root, Type service, Func`2 constraint, IEnumerable`1 parameters, Boolean isOptional, Boolean isUnique)
at Ninject.Extensions.Wcf.NinjectInstanceProvider.GetInstance(InstanceContext instanceContext, Message message) in C:\Development\ninject.extensions.wcf\source\Ninject.Extensions.Wcf\NinjectInstanceProvider.cs:line 75
at System.ServiceModel.Dispatcher.InstanceBehavior.GetInstance(InstanceContext instanceContext, Message request)
at System.ServiceModel.InstanceContext.GetServiceInstance(Message message)
at System.ServiceModel.Dispatcher.InstanceBehavior.EnsureServiceInstance(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
And here is the code I am using (pared down to only what's relevant):
In TheService.svc (no code-behind):
<%# ServiceHost Language="C#"
Debug="true"
Service="MyServices.TheService"
Factory="Ninject.Extensions.Wcf.NinjectServiceHostFactory"
%>
In Global.asax.cs:
public class Global : NinjectWcfApplication
{
protected override IKernel CreateKernel()
{
var kernel = new StandardKernel(new ServiceModule());
return kernel;
}
}
In ServiceModule.cs:
internal class ServiceModule : NinjectModule
{
public override void Load()
{
Bind<ITheService>().To<TheService>();
Bind<ITheRepository>().To<TheRepository>();
}
}
All of this code appears to work fine. I put some diagnostics in to trace the method calls and the CreateKernel method is called, followed by the call to the Load method in ServiceModule which returns then CreateKernel returns. However, I get the above exception when I try to call any of the service methods in TheService.
I'm using wsHttpBinding and the service references all resolve just fine. The interfaces and implementation classes are valid. It appears the problem is occurring when the actual service instance is being retrieved from the container/kernel.
What am I missing?

I had the same problem and found that the Kernel was not set in KernelContainer.Kernel (for version 2.2 https://github.com/ninject/ninject.extensions.wcf/blob/2.2.0.0/src/Ninject.Extensions.Wcf/KernelContainer.cs) or (for version 2.3 https://github.com/ninject/ninject.extensions.wcf/blob/2.3.0.0/src/Ninject.Extensions.Wcf/NinjectServiceHostFactory.cs) in NinjectServiceHostFactory.SetKernel(IKernel kernel).
Not sure why this isn't magically set, but setting it in the CreateKernel() method in Global.asax seems to fix it.

We encountered a similar regression issue which raised this exception (i.e. Ninject was previously working, and then suddenly threw :
Cannot be null. Parameter name: root at Ninject.ResolutionExtensions.GetResolutionIterator
It was eventually tracked down to a an unrelated bug in some ProtoBuf mapping bootstrapping code, which in turn had prevented Ninject from bootstrapping correctly.
So would recommend that you run your test suites on all of the following when tracking this down:
Static constructors and static readonly member initialization
AutoMapper map bootstrapping
Serialization map bootstrapping
etc.

Related

Ninject interception WCF service

I'm a newbie on the subject, so I'll try to make this as clear as I can...
I created a WcfModule, where I load the following package:
Bind<IDistributorService>().To<DistributorService>().InRequestScope().Intercept().With<ExceptionInterceptor>();
At first, I don't receive any error, but I put an InterceptAttribute on my function:
[AttributeUsage(AttributeTargets.Method)]
public sealed class HandleExceptionsAttribute : InterceptAttribute
{
public override IInterceptor CreateInterceptor(IProxyRequest request)
{
return request.Kernel.Get<ExceptionInterceptor>();
}
}
[HandleExceptions]
public virtual Result<List<DistributorDataContract>> GetDistributor(string id)
{
//...code...
I get an error in this function: (first line in method)
private ServiceHost CreateNewServiceHost(Type serviceType, Uri[] baseAddresses, WebHttpBehavior webBehavior, WebHttpBinding webHttpBinding)
{
var host = base.CreateServiceHost(serviceType, baseAddresses);
//...
}
With the error:
InvalidProxyConstructorArgumentsException was unhandled by user code
Can not instantiate proxy of class:
My.Namespace.DistributorService.
Could not find a parameterless constructor.
Anyone who knows what the problem could be? Thanks!
This exception is thrown by castle core dynamic proxy when it is instructed to create a "class proxy" which does not have a parameterless (default) constructor and no constructor-arguments are passed to castle (see source).
My best guess is, that when you use ninject interception by attributes, ninject will instruct castle core to create a class-proxy, no matter whether your binding is Bind<IFoo>().To<Foo>() or Bind<Foo>().ToSelf().
It seems a bit strange, however, that ninject is not resolving and passing along all required constructor parameters.
What is the implementation of DistributorService and what's the implementation of the base class of the class containing CreateNewServiceHost?
Workaround:
Of course, switching to the Intercept().With<TInterceptor>() syntax will probably also enable you to use interception (see http://codepyre.com/2010/03/using-ninject-extensions-interception-part-2-working-with-interceptors/)

WCF RIA Service with Unity 3.5.1.0

I'm trying to Use this Blog for WCF RIA Applcation . So I Create a Silverlight Nevigation Applciation which gave me 2 projects abs & abs.Web
More I create 3 project in solution :
abs.Data (c#), DbContext Implemeantion of Repository Interfaces +Factory to provide What user want.
abs.Data.Contarct (c#) Interfaces for Operations Repository
abs.Data.Model (c#) - Contains POCO - EF 6
Now I created A wcf Service in abs.Web project which have constructor injection of a Repository to get my job done in operation contracts.
So I tried using Unity here under the guidence with below blog
http://jamesheppinstall.wordpress.com/2012/06/20/windows-communication-foundation-resolving-wcf-service-dependencies-with-unity/
Now I'm getting
The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
**Stack Trace: **
[InvalidOperationException: The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.]
System.ServiceModel.Dispatcher.InstanceBehavior..ctor(DispatchRuntime dispatch, ImmutableDispatchRuntime immutableRuntime) +12761206
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime..ctor(DispatchRuntime dispatch) +173
System.ServiceModel.Dispatcher.DispatchRuntime.GetRuntimeCore() +85
System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpened() +148
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +321
System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) +139
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +310
System.ServiceModel.Channels.CommunicationObject.Open() +36
System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) +91
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +598
[ServiceActivationException: The service '/DomainServices/UserWcfService.svc' cannot be activated due to an exception during compilation. The exception message is: The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host..]
System.Runtime.AsyncResult.End(IAsyncResult result) +499812
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +178
System.ServiceModel.Activation.ServiceHttpHandler.EndProcessRequest(IAsyncResult result) +6
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18446
My all classes are same as like Blog.
WCF Ria has its own factory.
Simply put
public class MyDomainServiceFactory : IDomainServiceFactory
{
#region IDomainServiceFactory Members
public DomainService CreateDomainService(Type domainServiceType, DomainServiceContext context)
{
try
{
if (!typeof (DomainService).IsAssignableFrom(domainServiceType))
{
throw new ArgumentException(String.Format("Cannot create an instance of {0} since it does not inherit from DomainService", domainServiceType), "domainServiceType");
}
if (IoC.IsRegistered(domainServiceType))
{
var dmnService = (DomainService) IoC.Resolve(domainServiceType);
dmnService.Initialize(context);
return dmnService;
}
else
{
//if the IoC container doesn't know the service, simply try to call its default constructor
//could throw proper exception as well
var dmnService = (DomainService) Activator.CreateInstance(domainServiceType);
dmnService.Initialize(context);
return dmnService;
}
}
catch (Exception ex)
{
ExceptionHandler.HandleException(ex);
return null;
}
}
public void ReleaseDomainService(DomainService domainService)
{
domainService.Dispose();
}
#endregion
}
and somewhere on your bootstrapping code add
DomainService.Factory = new MyDomainServiceFactory();
of course, the word IoC in the factory identify the unityContainer (is actually a static façade against it)

WCF System.IndexOutOfRangeException in Dispatcher.DispatchOperationRuntime.InspectInputsCore

Issue: Getting below error while WCF service is invoked.
Index was outside the bounds of the array.
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InspectInputsCore(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
System.IndexOutOfRangeException
Need help to resolve this issue.
Details:
We have web-hosted (in same virtual directory, ASP.NET compatiblity enabled, baic http binding) multiple WCF services created as below
6 Services with individual service contracts for each service and respective datacontracts for each operations. Uses custom service host factory which adds a Message Inspector
2 services hosted in below fashion
2 seperate wsdls (design time files, with different schemas) pointing to the same service endpoint implementing the below contract. Uses a different custom service host factory which also adds a Message Inspector
[ServiceContract]
public interface IGenericService
{
[OperationContract(Action = "*", ReplyAction = "*")]
System.ServiceModel.Channels.Message GenericOperation(System.ServiceModel.Channels.Message msgRequest);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall,
ValidateMustUnderstand = false)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class GenericService : IGenericService
{
public Message GenericOperation(Message msgRequest)
{
All of these services are having proxies in SOA platform (Progress Actional). Actional maintains the direct endpoints for invoking the actual service and is able to properly invoke the actual service.
All 8 services are working fine in a server used for UnitTest execution. When deployed to QA servers all 6 services with individual service contracts work fine but the 2 new services (design time wsdls files) thow error listed above.
Code inside MessageInspector (failing services) looks as below. Other Inspector for other set of 6 services is similar.
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{
return Stopwatch.StartNew();
}
public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
Stopwatch watch = (Stopwatch)correlationState;
watch.Stop();
TimeSpan performanceTime = watch.Elapsed;
watch = null;
// Invoke Performance Logging Code
}
}
ServiceTrace looks as below.
Construct ServiceHost 'XyzServices.SpecificService' (One of the 6 service with individual service contract)
Open ServiceHost 'XyzServices.SpecificService'
All Endpoint listner opened for specific service
Listen at 'specificservice uri'
Processing message 1
Process action 'SpecificService.SpecificOperation.SoapAction'
Execute 'XyzServices.SpecificService.SpecificOperation'
Construct ServiceHost 'XyzServices.GenericService'
Processing message 2
From: Listen at 'XyzServices.SpecificService endpoint'
Activity boundary Start
To: Process action 'GenericService.GenericOperation.SoapAction'
To: Listen at 'XyzServices.SpecificService endpoint'
Activity boundary Stop
Open ServiceHost 'XyzServices.GenericService'
All Endpoint listner opened for Generic service
Process action 'GenericService.GenericOperation.SoapAction'
From: Processing message 2
Activity boundary Start
Received message over channel - Message header looks fine. Does not show message body
ServiceChannel information - Every thing looks fine here for (Unit Test server and QA server)
Handling an exception - shows the exception pasted in question details (only in QA server)
Sent a message over a channel
Aborted InstanceContext
Activity boundary Stop
(This activity looks fine when services run in Unit test server)
I used service trace viewer for the first time, but I noted that 'Processing message 2' activity starts from a activity which is related with the specific service. Does that indicate any problem in the way services are hosted. (where these services need separation)
Please let me know, if more details are needed.
this.InitializeCallContext(ref rpc);
object target = rpc.Instance;
this.DeserializeInputs(ref rpc);
**this.InspectInputs(ref rpc);**
ValidateMustUnderstand(ref rpc);
IAsyncResult result = null;
IDisposable impersonationContext = null;
IPrincipal originalPrincipal = null;
bool isThreadPrincipalSet = false;
try
{
if (this.parent.SecurityImpersonation != null)
{
this.parent.SecurityImpersonation.StartImpersonation(ref rpc, out impersonationContext, out originalPrincipal, out isThreadPrincipalSet);
}
void InspectInputsCore(ref MessageRpc rpc)
{
int offset = this.Parent.ParameterInspectorCorrelationOffset;
for (int i = 0; i < this.ParameterInspectors.Length; i++)
{
IParameterInspector inspector = this.ParameterInspectors[i];
rpc.Correlation[offset + i] = inspector.BeforeCall(this.Name, rpc.InputParameters);
}
}

ServiceStack Authenticate attribute results in null ref exception - pull request 267

I am making an MVC3 site using ServiceStacks authentication mechanism. When I add the AuthenticateAttribute to a controller, I get a null reference exception:
System.NullReferenceException was unhandled by user code
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=ServiceStack.FluentValidation.Mvc3
StackTrace:
at ServiceStack.Mvc.ExecuteServiceStackFiltersAttribute.OnActionExecuting(ActionExecutingContext filterContext) in C:\src\ServiceStack\src\ServiceStack.FluentValidation.Mvc3\Mvc\ExecuteServiceStackFiltersAttribute.cs:line 21
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
I can see in github that pull request #267 seems to make some null ref check exactly where my code currently throws. I have another project where authentication works, but the new failing code is running on a newer version of ServiceStack and I can't see what the difference is, so any ideas about what could cause this exception for new versions of service stack (v. 3.9.18)
Here is my configuration code:
Plugins.Add(new AuthFeature(
() => new AuthUserSession(), // Here a custom IAuthSession implementation could be used instead of UserSession.
// Allow authentication by using cookies set when authenticating with username/password credentials posted to the /auth/credentials service.
new IAuthProvider[]{ new CredentialsAuthProvider() }
)
);
//Enable Funq IOC in MVC controllers.
ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
IUserAuthRepository userRepository = new OrmLiteAuthRepository(dbFactory);
container.Register(userRepository);
container.Register<ICacheClient>(new MemoryCacheClient());
// Initialise Registration feature, providing the /register route.
Plugins.Add(new RegistrationFeature());
And my Controller base class:
public abstract class ControllerBase : ServiceStackController<AuthUserSession> {
public IDbConnectionFactory Db { get; set; }
public ILog Log { get; set; }
//Common extension point for all controllers. Inherits from ServiceStack to take advantage of SS powerpack + auth.
public override string LoginRedirectUrl {
get {
return "/Auth/Login?redirect={0}";
}
}
}
I've updated the ServiceStack.Mvc NuGet package that resolved a null reference exception in (v3.9.18+). Try updating and see if that resolves it.

Injecting dependencies into MVC3 WCF services using Ninject extensions

I have an MVC3 application which should expose some functions via WCF. Some of these functions have dependencies and I'd like to inject them using Ninject, but I must be missing something obvious here as this does not work. Could anyone give a hint? Here's what I did:
1) in my MVC3 app, I add Ninject Wcf extensions via nuget.
2) I add a .svc file like:
<%# ServiceHost Service="MyWeb.LookupService"
Factory="Ninject.Extensions.Wcf.NinjectServiceHostFactory"%>
3) I add the corresponding code like (that's just a test so I'm using a dummy interface right here):
[ServiceContract]
public interface ILookupService
{
[OperationContract]
int GetProjectIdByCode(string sCode);
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class LookupService : ILookupService
{
private readonly ISomeRepository _repository;
public LookupService(ISomeRepository repository)
{
_repository = repository;
}
public int GetProjectIdByCode(string sCode)
{
//... use _repository
}
}
4) in App_Start/NinjectMVC3.cs:
private static void RegisterServices(IKernel kernel)
{
string sConnection = ConfigurationManager.ConnectionStrings["SomeEntities"].ConnectionString;
// WCF
kernel.Bind<ServiceHost>().To<NinjectServiceHost>();
kernel.Bind<ISomeRepository>()
.To<AConcreteRepository>()
.WithConstructorArgument("sConnection", sConnection);
}
Now, when I access the svc I get the following exception from Ninject:
System.ArgumentNullException was unhandled by user code
Message=Cannot be null Parameter name: root Source=Ninject
ParamName=root StackTrace:
at Ninject.Infrastructure.Ensure.ArgumentNotNull(Object argument, String name) in
c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Infrastructure\Ensure.cs:line
20
at Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot
root, Type service, Func2 constraint, IEnumerable1 parameters,
Boolean isOptional, Boolean isUnique) in
c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line
258
at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root, IParameter[] parameters) in
c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line
37
at Ninject.Extensions.Wcf.NinjectServiceHostFactory.CreateServiceHost(Type
serviceType, Uri[] baseAddresses) in
c:\Projects\Ninject\Maintenance2.2\ninject.extensions.wcf\src\Ninject.Extensions.Wcf\NinjectServiceHostFactory.cs:line
48
at System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String
constructorString, Uri[] baseAddresses)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.CreateService(String
normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String
normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath)
Can you try to add a protected parameterless constructor to your implementation class.
Guess the servicehost needs a parameterless constructor as well.
I had a look at the Ninject service host factory and from the stack trace provided by you. It looks its failing whne making the following checks:
Ensure.ArgumentNotNull((object) root, "root");
Ensure.ArgumentNotNull((object) service, "service");
Ensure.ArgumentNotNull((object) parameters, "parameters");
Make sure that you are passing all the required parameters when using the NinjectServiceHostFactory. Worth trying to change the order of registration.
Also go through the following link here that explains how to use Ninject to host a wcf service.