Intergratin Autofac to ASP.NET WEPAPI with UnitOfWork to Create Single Database Context Instance or single unitofwork instance

205 views
Skip to first unread message

mck...@gmail.com

unread,
Oct 30, 2015, 6:33:24 AM10/30/15
to Autofac
+i created a UnitOfWork with entity framework DbContext initialization as private DbContext context = new DbContext(); All workings were great until i wanted to update a field in the database. The changes are reflected i the database, but the DbContext doesn't reflect the changes. However, adding a new record to the database has changes reflected in the DbContext, but not modification. I have to restart the application to see the changes. So, kind like the DbContext is not disposed after modification. So i decided to use Autofac to create a single database instance. This is my context:
public class DatabaseContext : IdentityDbContext<ApplicationUser>
{
static DatabaseContext()
{
Database.SetInitializer(new MySqlInitializer());
}


public DatabaseContext() : base("apiConnection") { }

public DbSet<PaperEntity> PastPapers { get; set; }
}


and i registered the context like this,
var builder = new ContainerBuilder();
builder.RegisterType<DatabaseContext>().AsSelf().SingleInstance();
//builder.RegisterType<UnitOfWork>().SingleInstance();


builder.RegisterApiControllers(typeof(AccountController).Assembly);
//builder.RegisterType<ISecureDataFormat<AuthenticationTicket>>().As<TicketDataFormat>();
//builder.RegisterApiControllers(Assembly.GetExecutingAssembly());


builder.RegisterType<SimpleAuthorizationServerProvider>()
.AsImplementedInterfaces<IOAuthAuthorizationServerProvider, ConcreteReflectionActivatorData>().SingleInstance();

container = builder.Build();

app.UseAutofacMiddleware(container);

var webApiDependencyResolver = new AutofacWebApiDependencyResolver(container);

var configuration = new HttpConfiguration
{
DependencyResolver = webApiDependencyResolver
};

ConfigureOAuth(app, container);

WebApiConfig.Register(configuration);

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

app.UseWebApi(configuration);

app.UseAutofacWebApi(configuration);


and i have an AccountController that looks like this
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
private readonly AccountService accountService;
public AccountController()
{
accountService = new AccountService();
}



private IAuthenticationManager Authentication
{
get { return Request.GetOwinContext().Authentication; }
}

[AllowAnonymous]
[HttpPost]
[Route("Register")]
public async Task<IHttpActionResult> Register([FromBody]RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

IdentityResult result = await accountService.RegisterUser(model, this);

return Ok(result);
}


the accountcontroller has an
private readonly AccountService accountService;
public AccountController()
{
accountService = new AccountService();
}


instance that has a unit of work instance like this...
private UnitOfWork unitOfWork;
public AccountService()
{
unitOfWork = new UnitOfWork();
}


Now, am somehow sure that i have configured Autofac well becouse authorization works with this,
AuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
Provider = container.Resolve<IOAuthAuthorizationServerProvider>(),
//AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
};


please note the Provider = container.Resolve<IOAuthAuthorizationServerProvider>() section. But when i try to get the DatabaseContext instance from the container in the UnitOfWork, like this,
private static IContainer Container { get; set; }
private DatabaseContext context = Container.BeginLifetimeScope().Resolve<DatabaseContext>();


everything stops to work, with the following error


"Message": "An error has occurred.", "ExceptionMessage": "An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor.", "ExceptionType": "System.InvalidOperationException", "StackTrace": " at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()

i want assistance to get the registered DatabaseContext without creating an interface for the context, or how to create an instance of UnitOfWork without an interface, or both, all i dont want are extra interfaces in the DatabaseContext, UnitOfWork, Or the Services, but preferably, if an interface is unavoidable, UnitOfWork would be the best place to have it...

Travis Illig

unread,
Oct 30, 2015, 9:28:06 AM10/30/15
to Autofac
It appears you have cross-posted this to StackOverflow already.

http://stackoverflow.com/q/33432710/8116

Please only post usage questions in one place (preferably StackOverflow) so we don't spend time trying to answer in two different spots.

I'll lock this thread so we can finish in StackOverflow.

Reply all
Reply to author
Forward
This conversation is locked
You cannot reply and perform actions on locked conversations.
0 new messages