Problems starting an NServiceBus - nservicebus

I've created a very simple NServiceBus console application to send messages. However I cannot start the bus as it complains with a very vague error about 'Object reference not set to an instance of an object'.
Configure config = Configure.With();
config = config.DefaultBuilder();
config = config.BinarySerializer();
config = config.UnicastBus();
IStartableBus startableBus = config.CreateBus();
IBus Bus2 = startableBus.Start(); // **barf**
It's driving me mad, what am I missing? I thought the DefaultBuilder should be filling in any blanks?

Hmm, looks like a reference to ncqrs.NserviceBus is causing it to go wrong even though I'm not actually using it yet

Looks like manually adding the Assemblies in the overload to With() did the trick, not sure what's upsetting it but that's for another day

Related

Programmatically modify web.config for a self-hosted service (not via changes to applicationHost.config)

I'm stuck on something I should probably move on from but it's driving me nuts...
I can programmatically update SSL certificate info for a self-hosted WCF service using:
Dim config As Microsoft.Web.Administration.Configuration = _
serverManager.GetApplicationHostConfiguration
site.Bindings.Clear()
Dim binding = site.Bindings.Add(ipport, cert.GetCertHash, store.Name)
serverManager.CommitChanges()
and can also change sections of my local web.config using a known file path starting with:
Dim cfg As System.Configuration.Configuration = _
System.Web.Configuration.WebConfigurationManager.OpenMappedWebConfiguration(ConfigFileMap, target)
but if I try to drill down to system.webServer/security/access using:
Dim accessSection = cfg.GetSection("system.webServer/security")
I get Nothing/null and further digging helpfully produces this status for the section "System.Configuration.IgnoreSection", which apparently indicates that System.Configuration doesn't want to play nice with that specific piece - even though it's not denied access in applicationHost as near as I can tell.
On the other hand, if I try to use Microsoft.Web.Administration I can only figure out how to make the change to applicationHost.config, not to the local web.config.
The only thing that seems to want to put the client certificate requirement (sslFlags setting) in the local web.config is IIS Manager (which also doesn't show the setting correctly if it is located in the applicationHost.config)
Obviously there are all sorts of ways to do this but I can't believe there isn't a simple dot net way (other than editing the xml). Does anyone know what the heck I am doing wrong?
Doh!!! Apparently I need to learn to read the manual (although MS doesn't make it easy).
You can simply do:
Using serverManager As New ServerManager
Dim config As Microsoft.Web.Administration.Configuration = _
serverManager.GetWebConfiguration("site name", "/application")
Dim accessSection As Microsoft.Web.Administration.ConfigurationSection = _
config.GetSection("system.webServer/security/access")
accessSection("sslFlags") = "Ssl,SslRequireCert"
serverManager.CommitChanges()
End Using
Retroactively obvious link: Relevant StackOverflow Question

Unable to determine the identity of domain using System.IO.Packaging

I am getting "Unable to determine the identity of domain" when using System.IO.Packaging through COM Interop, there are a few articles describing why this is happening and the solution is to run the offending function in its own AppDomain.
So I took the sample code, which looks like the below but I still get the error, I am wondering what i am doing wrong and also, with VS 2010 it says AddAssembly and AddHost are obsolete - I wonder if that means they are no longer implemented, but if thats the case I dont really understand how to use the new methods (AddAssemblyEvidence and AddHostEvidence)??
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
evidence.AddAssembly(Assembly.GetExecutingAssembly().FullName);
evidence.AddHost(new Zone(SecurityZone.MyComputer));
AppDomain domain = AppDomain.CreateDomain("BlobPackage", evidence, setup);
BlobPackage blob_interal = (BlobPackage)domain.CreateInstanceAndUnwrap(typeof(BlobPackage).Assembly.FullName, typeof(BlobPackage).FullName);
blob_interal.pack(FilePath, RootPath, m_source_files); <-- STILL FAILS
AppDomain.Unload(domain);
I solved this one myself, I forgot to inherit my class from MarshalByRefObject.
Its a bit stupid, it allows you to create an instance and call it except its still running in the default domain, you would think it would throw an exception or something, anyway by marking the class as [Serializable()] and deriving from MarshalByRefObject fixes it.

Autofac SingleInstance not working

I am trying to get a Singleton instance working with Autofac. I'm kind of doing a quasi-mvvm type thing with Winforms, just an experiment so don't get to hung up on that. But I am trying you have my model be a single instance with a reference in a command (ICommand here is not the WPF variety):
I have the following setup of a container:
var cb = new ContainerBuilder();
cb.RegisterType<CalculateCommissionCommand>().As<ICommand<TradeEntry>>().SingleInstance();
cb.RegisterType<CalculationsModel>().As<ICalculationsModel>().SingleInstance();
cb.Register(c => new CalculationsView() { Model = c.Resolve<ICalculationsModel>() }).SingleInstance();
cb.Build();
Now the Command takes an ICalculationsModel as a constructor parameter. However, when I set a value in the Model being passed to the Command, that value does not appear within the model that has already been set withing the CalculationsView. It seems that the command and the view are being passed different instances of the CalculationsModel despite the "singleInstance" method being called. Am I missing something? Why is this happening?
We hit a similar problem today and this seems to be the only post where this question is asked, so I thought I'd share our experience in the hopes it helps someone out. In the end it was something right in front of our eyes and of course they're usually the hardest problems to solve :-).
In our scenario, we were:
Registering a specific implementation of a configuration provider
Auto-registering certain types within an assembly.
Something along these lines:
var cb = new ContainerBuilder();
cb.RegisterType<FileBasedConfigurationProvider>()
.As<IConfigurationProvider>()
.SingleInstance();
cb.RegisterAssemblyTypes(typeof(MailProvider).Assembly)
.Where(t => !t.IsAbstract && t.Name.EndsWith("Provider"))
.AsImplementedInterfaces();
Stupidly, we didn't think about/realise that the FileBasedConfigurationProvider was in the same assembly as the MailProvider, so the second registration call basically overwrote the first one; hence, SingleInstance "wasn't working".
Hope that helps someone else out!
It's not clear from your code how you are storing/using the container. It is likely you have created multiple containers.
In my case the problem was that the parameter to the method generating the second instance was defined as the class instead of the interface
i.e.
SomeMethod(ClassName parameter)
instead of
SomeMethod(**I**ClassName parameter)
Obvious mistake, but took a few minutes to see it.
In my case I had two registrations for a class for different interfaces declaring that each was single instance. I assumed there would be a single instance of the class... no there's a single instance for each registration.
e.g
builder.RegisterType<MyClass>().As<IMyFirstInterface>().SingleInstance(); // 1st instance
builder.RegisterType<MyClass>().As<IMySecondInterface>().SingleInstance(); // 2nd instance
The correct way to do this was...
builder
.RegisterType<MyClass>()
.As<IMyFirstInterface>()
.As<IMySecondInterface>()
.SingleInstance();

Ninject: More than one matching bindings are available

I have a dependency with parameters constructor. When I call the action more than 1x, it show this error:
Error activating IValidationPurchaseService
More than one matching bindings are available.
Activation path:
1) Request for IValidationPurchaseService
Suggestions:
1) Ensure that you have defined a binding for IValidationPurchaseService only once.
public ActionResult Detalhes(string regionUrl, string discountUrl, DetalhesModel detalhesModel)
{
var validationPurchaseDTO = new ValidationPurchaseDTO {...}
KernelFactory.Kernel.Bind<IValidationPurchaseService>().To<ValidationPurchaseService>()
.WithConstructorArgument("validationPurchaseDTO", validationPurchaseDTO)
.WithConstructorArgument("confirmPayment", true);
this.ValidationPurchaseService = KernelFactory.Kernel.Get<IValidationPurchaseService>();
...
}
I'm not sure what are you trying to achieve by the code you cited. The error is raised because you bind the same service more than once, so when you are trying to resolve it it can't choose one (identical) binding over another. This is not how DI Container is supposed to be operated. In your example you are not getting advantage of your DI at all. You can replace your code:
KernelFactory.Kernel.Bind<IValidationPurchaseService>().To<ValidationPurchaseService>()
.WithConstructorArgument("validationPurchaseDTO", validationPurchaseDTO)
.WithConstructorArgument("confirmPayment", true);
this.ValidationPurchaseService = KernelFactory.Kernel.Get<IValidationPurchaseService>();
With this:
this.ValidationPurchaseService = new ValidationPurchaseService(validationPurchaseDTO:validationPurchaseDTO, confirmPayment:true)
If you could explain what you are trying to achieve by using ninject in this scenario the community will be able to assist further.
Your KernelFactory probably returns the same kernel (singleton) on each successive call to the controller. Which is why you add a similar binding every time you hit the URL that activates this controller. So it probably works the first time and starts failing after the second time.

How do I utilize a named instance within the ObjectFactory.Initialize call for StructureMap?

I am trying to do the following bootstrapping:
x.For(Of IErrorLogger).Use(Of ErrorLogger.SQLErrorLogger)().
Ctor(Of IErrorLogger)("backupErrorLogger").Is(ObjectFactory.GetNamedInstance(Of IErrorLogger)("Disk"))
x.For(Of IErrorLogger).Add(
Function()
Return New ErrorLogger.DiskErrorLogger(
CreateErrorFileName(ServerMapPath(GetAppSetting("ErrorLogFolder"))))
End Function).Named("Disk")
But it shows this error:
StructureMap Exception Code: 200
Could not find an Instance named "Disk" for PluginType Logging.IErrorLogger
I sort of understand why this is happening.. the question is, how do I utilize a named instance within the registry? Maybe something like lazy initialization for the ctor argument for the SQLErrorLogger? I am not sure how to make it happen.
Thanks in advance for any help you can provide.
I found the correct way to do it in the latest version (2.6.1) of StructureMap:
x.For(Of IErrorLogger).Use(Of ErrorLogger.SQLErrorLogger)().
Ctor(Of IErrorLogger)("backupErrorLogger").Is(
Function(c) c.ConstructedBy(Function() ObjectFactory.GetNamedInstance(Of IErrorLogger)("Disk"))
)
x.For(Of IErrorLogger).Add(Function() _
New ErrorLogger.DiskErrorLogger(
CreateErrorFileName(ServerMapPath(GetAppSetting("ErrorLogFolder"))))
).Named("Disk")
Notice for the Is method of Ctor, we need to provide a func(IContext), and use the IContext.ConstructedBy(Func()) to call ObjectFactory.Get... to successfully register the IErrorLogger in this case.
This is the only way to do it as far as I know. The other Icontext methods such as IsThis and Instance will only work with already registered type.
Your problem is that you are trying to access the Container before it's configured. In order to make structuremap evaluate the object resolution after the configuration you need to provide a lambda to the Is function. The lambda will be evaluated when trying to resolve the type registered.
x.[For](Of ILogger)().Add(Of SqlLogger)().Ctor(Of ILogger)("backupErrorLogger")_
.[Is](Function(context) context.GetInstance(Of ILogger)("Disk"))
x.[For](Of ILogger)().Add(Of DiskLogger)().Ctor(Of String)("errorFileName")_
.[Is](CreateErrorFileName(ServerMapPath(GetAppSetting("ErrorLogFolder"))))_
.Named("Disk")
Disclaimer: I'm not completely up-to-date with the lambda syntax in VB.NET, but I hope I got it right.
Edit:
The working C# version of this I tried myself before posting was this:
ObjectFactory.Initialize(i =>
{
i.For<ILogger>().Add<SqlLogger>()
.Ctor<ILogger>("backup").Is(
c => c.GetInstance<ILogger>("disk"))
.Named("sql");
i.For<ILogger>().Add<DiskLogger>().Named("disk");
});
var logger = ObjectFactory.GetNamedInstance<ILogger>("sql");