Is the default constructor really necessary for nhibernate to persist an object? - nhibernate

for some reason I don't wanna let user to create an instance of the object, without sending a property to the constructor
but as I know the object should have default constructor and so it would be possible to create an instance with out sending requierd property.
is there any way to prevent this problem? and if yes does it have any side effect?

Just use a protected default constructor:
public class Product
{
protected Product() { }
public Product(Category category)
{
this.Category = category;
}
}

"NHibernate allows a private default constructor for Value Objects, but for Entities you will need a default public or protected constructor as private is not sufficient."
Here you can find something:
https://github.com/davybrion/companysite-dotnet/blob/master/content/blog/2009-10-why-nhibernate-entities-need-a-public-or-protected-parameterless-constructor.md
Here there's an experiment to work without constructor:
http://kozmic.net/2011/03/20/working-with-nhibernate-without-default-constructors/
This is an example working with Dependency Injection:
http://nhibernate.info/blog/2008/12/12/entities-behavior-injection.html

Related

Kotlin: data class private setter public getter

Is there any way I can make a private setter and a public getter in a Kotlin Data Class?
data class Test(var attribute: String) {
// attribute can be mutated inside this class
// but outside only readable ?
}
A simple approach would be to have a private var, but then to provide a public property that delegates to it:
data class Test (private var attribute_ : String) {
val attribute: String get() = attribute_
}
To add some background to the other answer:
There's no way to do this directly in the constructor, though there have been several proposals as to how it could be added to the language; see here.
If it weren't a data class, I'd suggest this alternative:
class Test(_attribute: String) {
var attribute = _attribute
private set
}
That only stores one value in the object, so is marginally more efficient.
But since this is a data class, that's not possible.  (Data classes can't have non-properties in their primary constructors.)  So the other answer's suggestion seems best.

Deserializing IEnumerable with private backing field in RavenDb

I've been modeling a domain for a couple of days now and not been thinking at all at persistance but instead focusing on domain logic. Now I'm ready to persist my domain objects, some of which contains IEnumerable of child entities. Using RavenDb, the persistance is 'easy', but when loading my objects back again, all of the IEnumerables are empty.
I've realized this is because they don't have any property setters at all, but instead uses a list as a backing field. The user of the domain aggregate root can add child entities through a public method and not directly on the collection.
private readonly List<VeryImportantPart> _veryImportantParts;
public IEnumerable<VeryImportantPart> VeryImportantParts { get { return _veryImportantParts; } }
And the method for adding, nothing fancy...
public void AddVeryImportantPart(VeryImportantPart part)
{
// some logic...
_veryImportantParts.Add(part);
}
I can fix this by adding a private/protected setter on all my IEnumerables with backing fields but it looks... well... not super sexy.
private List<VeryImportantPart> _veryImportantParts;
public IEnumerable<VeryImportantPart> VeryImportantParts
{
get { return _veryImportantParts; }
protected set { _veryImportantParts = value.ToList(); }
}
Now the RavenDb json serializer will populate my objects on load again, but I'm curious if there isn't a cleaner way of doing this?
I've been fiddeling with the JsonContractResolver but haven't found a solution yet...
I think I've found the root cause of this issue and it's probably due to the fact that many of my entities were created using:
protected MyClass(Guid id, string name, string description) : this()
{ .... }
public static MyClass Create(string name, string description)
{
return new MyClass(Guid.NewGuid(), name, description);
}
When deserializing, RavenDb/Json.net couldn't rebuild my entities in a proper way...
Changing to using a public constructor made all the difference.
Do you need to keep a private backing field? Often an automatic property will do.
public IList<VeryImportantPart> VeryImportantParts { get; protected set; }
When doing so, you may want to initialize your list in the constructor:
VeryImportantParts = new List<VeryImportantPart>();
This is optional, of course, but it allows you to create a new class and start adding to the list right away, before it is persisted. When Raven deserializes a class, it will use the setter to overwrite the default blank list, so this just helps with the first store.
You certainly won't be able to use a readonly field, as it couldn't be replaced during deserialization. It might be possible to write a contract resolver or converter that fills an existing list rather than creating a new one, but that seems like a rather complex solution.
Using an automatic property can add clarity to your code anyway - as it is less confusing whether to use the field or the property.

Inheriting ConstructorArguments in Ninject

I'm trying to find a method of passing a constructor argument to the constructors of child classes.
These objects are immutable so I'd prefer to use constructor arguments.
The issue I have encountered is that ConstructorArgument does not inherit to child instantiations and the following statements are not interchangeable:
_parsingProcessor = _kernel.Get<IParsingProcessor>(new ConstructorArgument("dataFilePath", dataFilePath);
and
_parsingProcessor = _kernel.Get<IParsingProcessor>(new Parameter("dataFilePath", dataFilePath, true);
So, how can get an inheritable ConstructorArgument and when does it makes sense, if ever, to new the Parameter class?
Yes, you can do this, but it's probably not what you really want. If the container is not actually responsible for instantiating its own dependencies, then its dependencies probably shouldn't be sharing its constructor arguments - it just doesn't make sense.
I'm pretty sure I know what you're trying to do, and the recommended approach is to create a unique binding specifically for your one container, and use the WhenInjectedInto conditional binding syntax, as in the example below:
public class Hello : IHello
{
private readonly string name;
public Hello(string name)
{
this.name = name;
}
public void SayHello()
{
Console.WriteLine("Hello, {0}!", name);
}
}
This is the class that takes a constructor argument which we want to modify, depending on who is asking for an IHello. Let's say it's this boring container class:
public class MyApp : IApp
{
private readonly IHello hello;
public MyApp(IHello hello)
{
this.hello = hello;
}
public virtual void Run()
{
hello.SayHello();
Console.ReadLine();
}
}
Now, here's how you do up the bindings:
public class MainModule : NinjectModule
{
public override void Load()
{
Bind<IApp>().To<MyApp>();
Bind<IHello>().To<Hello>()
.WithConstructorArgument("name", "Jim");
Bind<IHello>().To<Hello>()
.WhenInjectedInto<MyApp>()
.WithConstructorArgument("name", "Bob");
}
}
Basically all this binding is doing is saying the name should be "Jim" unless it's being requested by Hello, which in this case it is, so instead it will get the name "Bob".
If you are absolutely certain that you truly want cascading behaviour and understand that this is very dangerous and brittle, you can cheat using a method binding. Assuming that we've now added a name argument to the MyApp class for some unspecified purpose, the binding would be:
Bind<IHello>().ToMethod(ctx =>
ctx.Kernel.Get<Hello>(ctx.Request.ParentContext.Parameters
.OfType<ConstructorArgument>()
.Where(c => c.Name == "name")
.First()));
Please, please, make sure you are positive that this is what you want before doing it. It looks easy but it is also very likely to break during a simple refactoring, and 95% of the "customized dependency" scenarios I've seen can be addressed using the WhenInjectedInto binding instead.

Is it OK to call virtual properties from the constructor of a NHibernate entity?

take a look at this example code:
public class Comment
{
private Comment()
{ }
public Comment(string text, DateTime creationDate, string authorEmail)
{
Text = text;
CreationDate = creationDate;
AuthorEmail = authorEmail;
}
public virtual string Text { get; private set; }
public virtual DateTime CreationDate { get; set; }
public virtual string AuthorEmail { get; private set; }
}
i know it's considered bad practice to call virtual member functions from the constructor, however in NHibernate i need the properties to be virtual to support lazy loading. Is it considered OK in this case?
I'm pretty sure this is fine, but if your worried you could always just assign the properties after a parameter less constructor call.
To expand on Paco's answer:
In most cases it doesn't hurt. But if the class is inherited, virtual allows the properties get/set to be overriden, so the behavior is no longer fully encapsulated and controlled, so it can break, in theory. FxCop warns about this because it's a potential problem.
The point of FxCop is to help warn you about potential problems though. It is not wrong to use properties in a constructor if you know you who/what is ever going to inherit from the class, but it isn't officially 'best practice'.
So, the answer is that it's fine as long as you control any inheritence of the class. Otherwise, don't use it and set the field values directly. (Which means you can't use C# 3.0 automatic get/set properties--you'll have to write properties wrapping fields yourself.)
Side note: Personally, all of my projects are web sites that we host for clients. So assuming this setup stays the same for a project, than it's worth the trade-off of having to duplicate the various null/argument checking. But, in any other case where I am not sure that we'll maintain complete control of the project and use of the class, I wouldn't take this shortcut.
It's OK in this sample, but it might cause problems when you inherit the class and override the properties. Generally, you can better create fields for the virtual properties.
IMHO the best-practice is to use properties with backing fields:
public class Comment
{
private DateTime _creationDate;
private string _text;
private string _authorEmail;
private Comment() { }
public Comment(string text, DateTime creationDate, string authorEmail)
{
_text = text;
_creationDate = creationDate;
_authorEmail = authorEmail;
}
public virtual string Text
{
get { return _text; }
private set { _text = value; }
}
public virtual string AuthorEmail
{
get { return _authorEmail; }
private set { _authorEmail = value; }
}
public virtual DateTime CreationDate
{
get { return _creationDate; }
set { _creationDate = value; }
}
}
So you can avoid problems on child classes and you don't see any warning anymore
I know that FxCop complains if you call a virtual method in your constructor, but I don't know what FxCop says whether you're calling a virtual property in your constructor ...
I would think that FxCop will complain as well since a property is translated to a method in IL.
You can also create your properties as 'non-virtual', and just specify 'lazy=false' on your 'class mapping' in NHIbernate.
This won't affect the lazy-load behavior of collections.
(I do it all the time, since I do not like that my infrastructure (NHibernate) requires me to have the properties virtual.
I also don't know whether the performance benefit of having dynamic proxies in NHibernate is significant).
I think, you should not call it in the constructor.
You can provide a method Initialize() which you can call after constructing the object.
In Initialize() you can call the required virtual methods

Ensuring only factory can create instance

class XFactory {
private XFactory() {}
static void getX() {
if(...)
return new A(new XFactory());
else
return new B(new XFactory());
}
}
class A {
private A() {}
public A(XFactory xf) {}
}
class B {
private B() {}
public A(XFactory xf) {}
}
By this way I can ensure only Factory can create instances of it's belonging Classes.
Is this right approach or there is any other alternative/good approach?
The common approach (in C++) is to make the "belonging classes" constructors private, and have them declare the factory class as friend.
I would make classes A and B friends of XFactory, and keep all their constructors private. Therefore, only XFactory has access to their constructors.
That is, in C++. In Java or C#, I don't see any clean way of enforcing that at compile-time. Your example is far from fool-proof and even a bit confusing, since as long as one has an instance of XFactory, he can pass it to the constructor of A or B and instantiate them directly like that.
If you were up for hacks and could not make your constructors private, you could:
Make your factory a global singleton and to create an object:
Create a random key
Add that key to a private list in the factory object of keys in use
Pass the key to the constructor
Have the constructor retrieve the global factory object and call it to validate the key.
If they key validation fails, scuttle your program (call exit, die, ... whatever is appropriate). Or possibly email a stack tract to an admin. This is the kind of thing that should be caught quickly.
(Do I get hack points?)
Jacob
In Java you can make the constructors private and provide the factory in the form of a public nested class, since nested classes have access to the private members of the class in which they are declared.
public class ExampleClass {
private ExampleClass() {
}
public class NestedFactory {
public ExampleClass createExample() {
return new ExampleClass();
}
}
Anyone who wanted to could create an instance of ExampleClass.NestedFactory and through it instantiate ExampleClasses.
I haven't been able to figure out a way to do this that lets you then inherit from ExampleClass since the Java compiler demands that you specify a constructor for the superclass... so that's a disadvantage.