Skip to content

Commit fc39c49

Browse files
committed
Add FAQ about ObjectDataSource controls
1 parent c7fd24f commit fc39c49

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

GETTING_STARTED.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,29 @@ Another advantage of this approach is that if you need to use a `DbContext` insi
186186
* `WebActivatorEx`'s `PreApplicationStartMethod` (the `PreStart` method in our sample above) runs **before** OWIN's Startup method.
187187
* See this StackOverflow post: https://stackoverflow.com/questions/21462777/webactivatorex-vs-owinstartup
188188

189+
### How to deal with `ObjectDataSource` controls
190+
Background: `ObjectDataSource` controls invoke a `Select` method defined in the `Page` object in order to retrieve the data to bind to other controls. This select method is usually a `static` method on the containing page, which prevents using DI, but can also be an instance method, in which case it instantiates a new `Page` object and calls the method on the newly created instance. That's the scenario when DI should be possible.
191+
192+
Unfortunately it seems that Microsoft never updated the `ObjectDataSource` control to use `HttpRuntime.WebObjectActivator`, so it's not able to instantiate DI-enabled `Page` controls. However, it is possible to override its `ObjectCreating` event to make it work the way we want:
193+
194+
```
195+
using System.Web;
196+
using System.Web.Compilation;
197+
using System.Web.UI.WebControls;
198+
...
199+
public class DiObjectDataSource: ObjectDataSource
200+
{
201+
public DiObjectDataSource()
202+
{
203+
this.ObjectCreating += (sender, args) =>
204+
args.ObjectInstance = HttpRuntime.WebObjectActivator.GetService(Type.GetType(BuildManager.GetType(
205+
((ObjectDataSourceView) sender).TypeName, throwOnError: false, ignoreCase: true));
206+
}
207+
}
208+
```
209+
210+
We need to use `BuildManager.GetType` instead of `Type.GetType` because this method is actually able to look for the type in all of the application assemblies - otherwise we'd be restricted to the current assembly types.
211+
189212
## Included services
190213

191214
All included services are exposed as interfaces so you can replace them with your own implementation for testing purposes or for different production scenarios. They are listed below:

0 commit comments

Comments
 (0)