what is the replacement for Application_Start in MVCTurbine? - c#

Apparently, this method no longer gets called... In there we have code for configuring AutoMapper, and for setting model binders.
I know there is a "new" way to do model binders, but... shouldn't I still be able to do it "the old way" until I get that implemented?
Specifically, I have two lines left from my old Application_Start() method that I have been unable to get working:
AutoMapperConfiguration.Configure();
ModelBinders.Binders[typeof (ModuleEditModel)] = new DerivedModelBinder();
I've tried simply popping those into the constructor, right after the call to: ServiceLocatorManager.SetLocatorProvider(() => new StructureMapServiceLocator());
And that runs, but.. it seems somehow not to take effect. In running the application it is clear that AutoMapper isn't happy, doesn't have the mappings it is supposed to have, etc.

I answered this question out on the Turbine Discussion board on CodePlex. Here's the source for making the changes you ask for:
public class MvcApplication : TurbineApplication {
static MvcApplication() {
// Register the IoC that you want Mvc Turbine to use!
// Everything else is wired automatically
// For now, let's use the Unity IoC
ServiceLocatorManager.SetLocatorProvider(() => new UnityServiceLocator());
}
public override void Startup(){
// Gets called when the application starts up
// and before all the stuff that Turbine wires up
}
public override void Shutdown() {
// Gets called when the application shuts down
// and before any cleanup is done by Turbine
}
}
Hope this helps!

Related

DevExpress XAF - Test if an object is registred before executing code in ViewController

I'm developing using DevExpress XAF, my problem is a little bit tricky, in short, when I save my class I make changes in other classes based on the data provided, I realized this with a controller that executes code when I close the detail view, the problem is that there is a scenario that does not meet my needs, here is it:
When I open a detail view already existing and that I modify some data, when I close the window, the program displays a window of confirmation ("do you want to register?) when I click on no, normally my view controller will not do anything because I refused to change my class data
Finally here is my question: How to test in my view controller if the object was registered or not before proceeding to the change and execute my code?
When you say register, I think you mean save.
You can use the ObjectSpace.GetObjectsToSave() method to obtain a list of objects which will be saved when ObjectSpace.CommitChanges() is called. You can then determine whether View.CurrentObject is in this list.
Alternatively you could use the ObjectSpace_ObjectChanged event. Something like this.
public class MyViewController : ObjectViewController<DetailView, Contact> {
protected override void OnActivated() {
base.OnActivated();
ObjectSpace.ObjectChanged += ObjectSpace_ObjectChanged;
}
void ObjectSpace_ObjectChanged(object sender, ObjectChangedEventArgs e) {
if (e.Object == View.CurrentObject) {
// execute your business logic
}
}
protected override void OnDeactivated() {
base.OnDeactivated();
ObjectSpace.ObjectChanged -= ObjectSpace_ObjectChanged;
}
}
See here for a Support Center discussion of a similar request.

How to locally disable optimization

I faced with strange problem. My app has next code, that execute on startup:
protected override void RegisterTypes()
{
// App.container - UnityContainer
var dvcc = new MyClientCore(new MySorter());
App.container.RegisterInstance(typeof(ClientCore), dvcc);
App.container.RegisterInstance(typeof(MyClientCore), dvcc);
this.dataProvider = new MyProvider();
this.dataProvider.Configure(App.container);
App.container.RegisterInstance(typeof(Provider), this.dataProvider);
App.container.RegisterInstance(typeof(MyProvider), this.dataProvider);
// Create view models and register them in container
this.RegisterViewModels();
// Command - singleton, that resolved in ctor view models,
// that registered in RegisterViewModels();
Command.Instance.InitCommands();
// Create and configure shell
}
When app execute in debug configuration there are no problem. Also when app execute in release configuration in visual studio.
But when I try to start app directly I get TypeInitializationException in Command ctor because of resolution of the dependency registered in dataProvider.Configure method.
I thought that cause in JIT optimization, and code may be execute like
protected override void RegisterTypes()
{
Command.Instance.InitCommands();
// other method body
}
I found solution for that - mark RegisterTypes method atribute [MethodImpl(MethodImplOptions.NoOptimization)].
But maybe exist better method to fix it? Also I will be gratiful for link, when that situation explained with simple words.
P.S. Sorry for my english.

Nancy create singleton with constructor parameters

I'm using Nancy with TinyIoC to solve the dependencies.
One dependency in particular needs to be application-lifecycle singleton.
If I do it with a default constructor it works:
container.Register<IFoo, Foo>().AsSingleton(); // WORKS
but if i try this with some arguments on the contructor it does not:
container.Register<IFoo>((c, e) => new Foo("value", c.Resolve<ILogger>())).AsSingleton();
// FAILS with error "Cannot convert current registration of Nancy.TinyIoc.TinyIoCContainer+DelegateFactory to singleton"
Whithout .AsSingleton(), it works again, but I don't get a singleton:
container.Register<IFoo>((c, e) => new Foo("value", c.Resolve<ILogger>()));
// Works, but Foo is not singleton
Any Ideas? I think the mistake should be obvious but I can't find it.
I've used up all my google-foo.
EDIT
The code runs here:
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
base.ConfigureApplicationContainer(container);
// here
}
}
What you're doing there is telling TinyIOC "every time you want one of these, call my delegate", so if you want to use that method you have to handle the singleton aspect yourself.
Unless you particularly need the deferred creation it's easier to do:
container.Register<IFoo>(new Foo("value", c.Resolve<ILogger>()));
That will then always use that instance whenever you want an IFoo.

Structuremap - Override registration

Is it possible to register an interface in a registry, then "re-register" it to override the first registration?
I.E.:
For<ISomeInterface>().Use<SomeClass>();
For<ISomeInterface>().Use<SomeClassExtension>();
What I want here on runtime is that my object factory returns SomeClassExtension when I ask for ISomeInterface.
Thanks in advance!
Good news, I found out that yes. It all depends on the order that the registry rules are added to the object factory container. So if you are using multiple registry classes as I was doing, you need to find a way to give a priority to add them to the container.
In other words, instead of using the .LookForRegistries() which gets all the Registry classes in the wrong order, try to find all the Registry files, set them in the order you want and add them manually to the object factory container:
ObjectFactory.Container.Configure(x => x.AddRegistry(registry));
That way, you have full control on what rules you want.
Hope it helps :)
I just wanted to add my solution to the problem when I needed to override some parts of a registry in my SpecFlow test.
I did find this thread pretty early in my search, but it didnĀ“t really help me find the solution, so I hope it will help you.
My problem was that the "DataContext" in "StoreRegistry" (used by the application) use the "HybridHttpOrThreadLocalScoped" and I needed it to be "Transient" in my tests.
The code looked like this:
[Binding]
public class MySpecFlowContext
{
...
[BeforeFeature]
private static void InitializeObjectFactories()
{
ObjectFactory.Initialize(x =>
{
x.AddRegistry<StoreRegistry>();
x.AddRegistry<CommonRegistry>();
});
}
}
To override the scope setting you will need to explicitly set it in the registration.
And the override needs to be below what is overridden
The working code looks like this:
[Binding]
public class MySpecFlowContext
{
...
[BeforeFeature]
private static void InitializeObjectFactories()
{
ObjectFactory.Initialize(x =>
{
x.AddRegistry<StoreRegistry>();
x.AddRegistry<CommonRegistry>();
x.AddRegistry<RegistryOverrideForTest>();
});
}
class RegistryOverrideForTest : Registry
{
public RegistryOverrideForTest()
{
//NOTE: type of scope is needed when overriding the registered classes/interfaces, when leaving it empty the scope will be what was registered originally, f ex "HybridHttpOrThreadLocalScoped" in my case.
For<DataContext>()
.Transient()
.Use<DataContext>()
.Ctor<string>("connection").Is(ConnectionBuilder.GetConnectionString());
}
}
}

Unity - resolving without resolve()

I would like to just markup a property with an attribute [DoInjection] and have unity do the injection. I don't want to have to use prop = Unity.Resolve(type). Thats a pain and messy. Does unity provide attributes to do this or do I have to build my own?
Edit: register in App.Main
ISessionFactory sf = new SessionFactory();
container.RegisterType<IRepository, CustomerRepository>(new InjectionConstructor(sf.CurrentUoW));
container.RegisterInstance<IUnitOfWork>(sf.CurrentUoW);
Using [Dependancy] on IUnitOfWork propery in ClassX other class but it's always null. Do I need to build ClassX instance using Unity to get this to work? It looks like I do have to. I don't like that.
Unity has a DependencyAttribute you can use for this:
public class MyObject
{
private SomeOtherObject _dependentObject;
[Dependency]
public SomeOtherObject DependentObject
{
get { return _dependentObject; }
set { _dependentObject = value; }
}
}
http://msdn.microsoft.com/en-us/library/ff650198.aspx
Based on your question, it sounds like you might be trying to use Unity in the wrong spot and your design sense was telling you it didn't feel right. You should only see Unity where you bootstrap your application. That's your Main method in a console app or Global.asax in a web or wcf app. The idea is to keep relying on dependencies all the way up the chain until you get to where you bootstrap and resolve just that one top level object using your IoC container. In a console app, I do this:
class Program
{
static void Main(string[] args)
{
using (var container = new UnityContainer())
{
container
.AddExtension(new ConfigureForConsole(args))
.Resolve<MyApplication>()
.Execute();
}
}
}
http://www.agileatwork.com/console-application-with-ioc/
In this case, MyApplication is my top level object (it doesn't need to be an interface here). The ConfigureForConsole is just a one-off custom container extension that has all the RegisterType lines in there. Alternatively you could initialize the container from App.Config here. The idea though is that your Main method has almost nothing in it. Another benefit of this approach is that it makes your code more portable. I find that console apps usually turn into windows services and keeping things clean here makes that transition pretty painless.

Categories

Resources