Case:
Opf3 uses an ObjectContext class to connect with the database and work with your business entities and such, so generally you should be able to access the static method you need to get this object from every single part of your application imaginable, right? So if you're working with WCSF you'll probably need to use a Foundational Module.
This all shouldn't really be a problem if you have presenters and views everywhere that derive from the Microsoft.Practices.CompositeWeb.Web.UI.Page class. Even if you have some pages that don't have a presenter you can make them derive from the CompositeWeb's Page class, so then your problem is fixed too. But what to do when you have a class that derives from MembershipProvider, or custom server controls?
Theory:
The ObjectBuilder goes through classes that derive from certain CompositeWeb classes and searches for attributes like ServiceDependency, InjectionConstructor, CreateNew and such. You can make a public property with a ServiceDependency attribute so that any dependencies are handled and your compiler won't complain about there not being an argumentless constructor.
Problem:
Classes that don't derive from CompositeWeb classes don't get the benefit of this ObjectBuilder.
Solution:
After many hours of trying, searching, researching and asking around I finally found out how to fix this. Being inexperienced as I am, though, doesn't make me at all certain if there's something wrong with this approach, but if you create an argumentless constructor and call the Microsoft.Practices.CompositeWeb.WebClientApplication.BuildItemWithCurrentContext(this) function, the ObjectBuilder will run through your class and use these attributes.
Code:
using System;
using Microsoft.Practices.CompositeWeb;
using Microsoft.Practices.ObjectBuilder;
using Chili.Opf3;
namespace Your.Namespace.Here
{
class MyClass : SomeClassItDerivesFrom
{
private ObjectContext _objContext; // The ObjectContext Opf3 uses to work with the database.
private IContextService _objContextFactory; // The Service you made with the static function.
[ServiceDependency] // This won't work without the function we call in the constructor
public IContextService ObjContextFactory
{
set
{
_objContextFactory = value;
_objContext = _objContextFactory.GetObjectContext(); // The static function you should have made.
}
}
public MyClass()
{
WebClientApplication.BuildItemWithCurrentContext(this);
}
private SomeFunction()
{
ObjectSetobjectSet = _objContext.GetObjectContext ();
// Well, you should know what to do next.
}
}
}
Comments:
Well, having never done anything like this before in my life I hope this is all and it might help someone. I've searched the internet for hours without any luck really, so maybe it will be helpful

Thank You for the help!
ReplyDeleteThanks a mil you are a star, just spent ages on this.
ReplyDeleteI was helpful. Thanks.
ReplyDelete